-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
EntityManager.ts
711 lines (578 loc) · 28.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
import { v4 as uuid } from 'uuid';
import { inspect } from 'util';
import { Configuration, QueryHelper, RequestContext, Utils, ValidationError } from './utils';
import { EntityAssigner, EntityFactory, EntityLoader, EntityRepository, EntityValidator, IdentifiedReference, LoadStrategy, Reference, ReferenceType, wrap } from './entity';
import { LockMode, UnitOfWork } from './unit-of-work';
import { CountOptions, DeleteOptions, EntityManagerType, FindOneOptions, FindOneOrFailOptions, FindOptions, IDatabaseDriver, UpdateOptions } from './drivers';
import { AnyEntity, Dictionary, EntityData, EntityMetadata, EntityName, FilterDef, FilterQuery, Loaded, Primary, Populate, PopulateMap, PopulateOptions, New, GetRepository } from './typings';
import { QueryOrderMap } from './enums';
import { MetadataStorage } from './metadata';
import { Transaction } from './connections';
import { EventManager } from './events';
/**
* 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.
*/
export class EntityManager<D extends IDatabaseDriver = IDatabaseDriver> {
readonly id = uuid();
private readonly validator = new EntityValidator(this.config.get('strict'));
private readonly repositoryMap: Dictionary<EntityRepository<AnyEntity>> = {};
private readonly entityLoader: EntityLoader = new EntityLoader(this);
private readonly unitOfWork = new UnitOfWork(this);
private readonly entityFactory = new EntityFactory(this.unitOfWork, this);
private readonly eventManager = new EventManager(this.config.get('subscribers'));
private filters: Dictionary<FilterDef<any>> = {};
private filterParams: Dictionary<Dictionary> = {};
private transactionContext?: Transaction;
constructor(readonly config: Configuration,
private readonly driver: D,
private readonly metadata: MetadataStorage,
private readonly useContext = true) { }
/**
* Gets the Driver instance used by this EntityManager
*/
getDriver(): D {
return this.driver;
}
/**
* Gets the Connection instance, by default returns write connection
*/
getConnection(type?: 'read' | 'write'): ReturnType<D['getConnection']> {
return this.driver.getConnection(type) as ReturnType<D['getConnection']>;
}
/**
* Gets repository for given entity. You can pass either string name or entity class reference.
*/
getRepository<T extends AnyEntity<T>, U extends EntityRepository<T> = EntityRepository<T>>(entityName: EntityName<T>): GetRepository<T, U> {
entityName = Utils.className(entityName);
if (!this.repositoryMap[entityName]) {
const meta = this.metadata.get(entityName);
const RepositoryClass = this.config.getRepositoryClass(meta.customRepository)!;
this.repositoryMap[entityName] = new RepositoryClass(this, entityName);
}
return this.repositoryMap[entityName] as unknown as GetRepository<T, U>;
}
/**
* 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<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, options?: FindOptions<T, P>): Promise<Loaded<T, P>[]>;
/**
* Finds all entities matching your `where` query.
*/
async find<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, populate?: P, orderBy?: QueryOrderMap, limit?: number, offset?: number): Promise<Loaded<T, P>[]>;
/**
* Finds all entities matching your `where` query.
*/
async find<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, populate?: P | FindOptions<T, P>, orderBy?: QueryOrderMap, limit?: number, offset?: number): Promise<Loaded<T, P>[]> {
const options = Utils.isObject<FindOptions<T, P>>(populate) ? populate : { populate, orderBy, limit, offset } as FindOptions<T, P>;
entityName = Utils.className(entityName);
where = QueryHelper.processWhere(where, entityName, this.metadata);
where = await this.applyFilters(entityName, where, options.filters ?? {}, 'read');
this.validator.validateParams(where);
options.orderBy = options.orderBy || {};
options.populate = this.preparePopulate<T>(entityName, options.populate, options.strategy) as unknown as P;
const results = await this.driver.find<T>(entityName, where, options, this.transactionContext);
if (results.length === 0) {
return [];
}
const ret: T[] = [];
for (const data of results) {
const entity = this.merge<T>(entityName, data, options.refresh);
ret.push(entity);
}
const unique = Utils.unique(ret);
await this.entityLoader.populate<T>(entityName, unique, options.populate as unknown as PopulateOptions<T>[], { ...options, where });
return unique as Loaded<T, P>[];
}
addFilter<T1>(name: string, cond: FilterQuery<T1> | ((args: Dictionary) => FilterQuery<T1>), entityName?: EntityName<T1> | [EntityName<T1>], enabled?: boolean): void;
addFilter<T1, T2>(name: string, cond: FilterQuery<T1 | T2> | ((args: Dictionary) => FilterQuery<T1 | T2>), entityName?: [EntityName<T1>, EntityName<T2>], enabled?: boolean): void;
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;
addFilter(name: string, cond: FilterQuery<AnyEntity> | ((args: Dictionary) => FilterQuery<AnyEntity>), entityName?: EntityName<AnyEntity> | EntityName<AnyEntity>[], enabled = true): void {
const options: FilterDef<AnyEntity> = { name, cond, default: enabled };
if (entityName) {
options.entity = Utils.asArray(entityName).map(n => Utils.className(n));
}
this.filters[name] = options;
}
setFilterParams(name: string, args: Dictionary): void {
this.filterParams[name] = args;
}
protected async applyFilters<T>(entityName: string, where: FilterQuery<T>, options: Dictionary<boolean | Dictionary> | string[] | boolean, type: 'read' | 'update' | 'delete'): Promise<FilterQuery<T>> {
const meta = this.metadata.find<T>(entityName);
const filters: FilterDef<any>[] = [];
const ret = {};
if (!meta) {
return where;
}
filters.push(...QueryHelper.getActiveFilters(entityName, options, this.config.get('filters')));
filters.push(...QueryHelper.getActiveFilters(entityName, options, this.filters));
filters.push(...QueryHelper.getActiveFilters(entityName, options, meta.filters));
if (filters.length === 0) {
return where;
}
if (Utils.isPrimaryKey(where) && meta.primaryKeys.length === 1) {
where = { [meta.primaryKeys[0]]: where } as FilterQuery<T>;
}
for (const filter of filters) {
let cond: Dictionary;
if (filter.cond instanceof Function) {
const args = Utils.isPlainObject(options[filter.name]) ? options[filter.name] : this.filterParams[filter.name];
if (!args) {
throw new Error(`No arguments provided for filter '${filter.name}'`);
}
cond = await filter.cond(args, type);
} else {
cond = filter.cond;
}
const cond2 = QueryHelper.processWhere(cond, entityName, this.metadata);
Utils.merge(ret, cond2, where);
}
return Object.assign(where, ret);
}
/**
* 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<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, options?: FindOptions<T, P>): Promise<[Loaded<T, P>[], number]>;
/**
* 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<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, populate?: P, orderBy?: QueryOrderMap, limit?: number, offset?: number): Promise<[Loaded<T, P>[], number]>;
/**
* 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<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, populate?: P | FindOptions<T, P>, orderBy?: QueryOrderMap, limit?: number, offset?: number): Promise<[Loaded<T, P>[], number]> {
const [entities, count] = await Promise.all([
this.find<T, P>(entityName, where, populate as P, orderBy, limit, offset),
this.count(entityName, where),
]);
return [entities, count];
}
/**
* Finds first entity matching your `where` query.
*/
async findOne<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, options?: FindOneOptions<T, P>): Promise<Loaded<T, P> | null>;
/**
* Finds first entity matching your `where` query.
*/
async findOne<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, populate?: P, orderBy?: QueryOrderMap): Promise<Loaded<T, P> | null>;
/**
* Finds first entity matching your `where` query.
*/
async findOne<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, populate?: P | FindOneOptions<T, P>, orderBy?: QueryOrderMap): Promise<Loaded<T, P> | null> {
entityName = Utils.className(entityName);
const options = Utils.isObject<FindOneOptions<T, P>>(populate) ? populate : { populate, orderBy } as FindOneOptions<T, P>;
const meta = this.metadata.get<T>(entityName);
where = QueryHelper.processWhere(where as FilterQuery<T>, entityName, this.metadata);
where = await this.applyFilters(entityName, where, options.filters ?? {}, 'read');
this.validator.validateEmptyWhere(where);
this.checkLockRequirements(options.lockMode, meta);
let entity = this.getUnitOfWork().tryGetById<T>(entityName, where);
const isOptimisticLocking = !Utils.isDefined(options.lockMode) || options.lockMode === LockMode.OPTIMISTIC;
if (entity && wrap(entity).isInitialized() && !options.refresh && isOptimisticLocking) {
return this.lockAndPopulate<T, P>(entityName, entity, where, options);
}
this.validator.validateParams(where);
options.populate = this.preparePopulate<T>(entityName, options.populate as true, options.strategy) as unknown as P;
const data = await this.driver.findOne(entityName, where, options, this.transactionContext);
if (!data) {
return null;
}
entity = this.merge(entityName, data as EntityData<T>, options.refresh) as T;
await this.lockAndPopulate(entityName, entity, where, options);
return entity as Loaded<T, P>;
}
/**
* Finds first entity matching your `where` query. If nothing found, it will throw an error.
* You can override the factory for creating this method via `options.failHandler` locally
* or via `Configuration.findOneOrFailHandler` globally.
*/
async findOneOrFail<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, options?: FindOneOrFailOptions<T, P>): Promise<Loaded<T, P>>;
/**
* Finds first entity matching your `where` query. If nothing found, it will throw an error.
* You can override the factory for creating this method via `options.failHandler` locally
* or via `Configuration.findOneOrFailHandler` globally.
*/
async findOneOrFail<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, populate?: P, orderBy?: QueryOrderMap): Promise<Loaded<T, P>>;
/**
* Finds first entity matching your `where` query. If nothing found, it will throw an error.
* You can override the factory for creating this method via `options.failHandler` locally
* or via `Configuration.findOneOrFailHandler` globally.
*/
async findOneOrFail<T, P extends Populate<T> = any>(entityName: EntityName<T>, where: FilterQuery<T>, populate?: P | FindOneOrFailOptions<T, P>, orderBy?: QueryOrderMap): Promise<Loaded<T, P>> {
const entity = await this.findOne(entityName, where, populate as string[], orderBy);
if (!entity) {
const options = Utils.isObject<FindOneOrFailOptions<T>>(populate) ? populate : {};
options.failHandler = options.failHandler || this.config.get('findOneOrFailHandler');
entityName = Utils.className(entityName);
throw options.failHandler!(entityName, where);
}
return entity as Loaded<T, P>;
}
/**
* Runs your callback wrapped inside a database transaction.
*/
async transactional<T>(cb: (em: D[typeof EntityManagerType]) => Promise<T>, ctx = this.transactionContext): Promise<T> {
const em = this.fork(false);
return em.getConnection().transactional(async trx => {
em.transactionContext = trx;
const ret = await cb(em);
await em.flush();
return ret;
}, ctx);
}
/**
* Runs your callback wrapped inside a database transaction.
*/
async lock(entity: AnyEntity, lockMode: LockMode, lockVersion?: number | Date): Promise<void> {
await this.getUnitOfWork().lock(entity, lockMode, lockVersion);
}
/**
* Fires native insert query. Calling this has no side effects on the context (identity map).
*/
async nativeInsert<T>(entityName: EntityName<T>, data: EntityData<T>): Promise<Primary<T>> {
entityName = Utils.className(entityName);
data = QueryHelper.processParams(data);
this.validator.validateParams(data, 'insert data');
const res = await this.driver.nativeInsert(entityName, data, this.transactionContext);
return res.insertId as Primary<T>;
}
/**
* Fires native update query. Calling this has no side effects on the context (identity map).
*/
async nativeUpdate<T>(entityName: EntityName<T>, where: FilterQuery<T>, data: EntityData<T>, options: UpdateOptions<T> = {}): Promise<number> {
entityName = Utils.className(entityName);
data = QueryHelper.processParams(data);
where = QueryHelper.processWhere(where as FilterQuery<T>, entityName, this.metadata);
where = await this.applyFilters(entityName, where, options.filters ?? {}, 'update');
this.validator.validateParams(data, 'update data');
this.validator.validateParams(where, 'update condition');
const res = await this.driver.nativeUpdate(entityName, where, data, this.transactionContext);
return res.affectedRows;
}
/**
* Fires native delete query. Calling this has no side effects on the context (identity map).
*/
async nativeDelete<T>(entityName: EntityName<T>, where: FilterQuery<T>, options: DeleteOptions<T> = {}): Promise<number> {
entityName = Utils.className(entityName);
where = QueryHelper.processWhere(where as FilterQuery<T>, entityName, this.metadata);
where = await this.applyFilters(entityName, where, options.filters ?? {}, 'delete');
this.validator.validateParams(where, 'delete condition');
const res = await this.driver.nativeDelete(entityName, where, this.transactionContext);
return res.affectedRows;
}
/**
* Maps raw database result to an entity and merges it to this EntityManager.
*/
map<T>(entityName: EntityName<T>, result: EntityData<T>): T {
entityName = Utils.className(entityName);
const meta = this.metadata.get(entityName);
const data = this.driver.mapResult(result, meta)!;
return this.merge<T>(entityName, data, true);
}
/**
* Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
* via second parameter. By default it will return already loaded entities without modifying them.
*/
merge<T>(entity: T, refresh?: boolean): T;
/**
* Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
* via second parameter. By default it will return already loaded entities without modifying them.
*/
merge<T>(entityName: EntityName<T>, data: EntityData<T>, refresh?: boolean): T;
/**
* Merges given entity to this EntityManager so it becomes managed. You can force refreshing of existing entities
* via second parameter. By default it will return already loaded entities without modifying them.
*/
merge<T>(entityName: EntityName<T> | T, data?: EntityData<T> | boolean, refresh?: boolean): T {
if (Utils.isEntity(entityName)) {
return this.merge(entityName.constructor.name, entityName as EntityData<T>, data as boolean);
}
entityName = Utils.className(entityName as string);
this.validator.validatePrimaryKey(data as EntityData<T>, this.metadata.get(entityName));
let entity = this.getUnitOfWork().tryGetById<T>(entityName, data as FilterQuery<T>, false);
if (entity && wrap(entity).isInitialized() && !refresh) {
return entity;
}
entity = Utils.isEntity<T>(data) ? data : this.getEntityFactory().create<T>(entityName, data as EntityData<T>);
// add to IM immediately - needed for self-references that can be part of `data` (do not trigger cascade merge)
this.getUnitOfWork().merge(entity, [entity]);
EntityAssigner.assign(entity, data as EntityData<T>, { onlyProperties: true, merge: true });
this.getUnitOfWork().merge(entity); // add to IM again so we have correct payload saved for change set computation
return entity;
}
/**
* Creates new instance of given entity and populates it with given data
*/
create<T, P extends Populate<T> = string[]>(entityName: EntityName<T>, data: EntityData<T, P>): New<T, P> {
return this.getEntityFactory().create<T, P>(entityName, data, true, true);
}
/**
* Shortcut for `wrap(entity).assign(data, { em })`
*/
assign<T>(entity: T, data: EntityData<T>): T {
return EntityAssigner.assign(entity, data, { em: this });
}
/**
* Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
*/
getReference<T, PK extends keyof T>(entityName: EntityName<T>, id: Primary<T>, wrapped: true): IdentifiedReference<T, PK>;
/**
* Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
*/
getReference<T>(entityName: EntityName<T>, id: Primary<T> | Primary<T>[]): T;
/**
* Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
*/
getReference<T>(entityName: EntityName<T>, id: Primary<T>, wrapped: false): T;
/**
* Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
*/
getReference<T>(entityName: EntityName<T>, id: Primary<T>, wrapped: boolean): T | Reference<T>;
/**
* Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
*/
getReference<T>(entityName: EntityName<T>, id: Primary<T>, wrapped = false): T | Reference<T> {
const meta = this.metadata.get(Utils.className(entityName));
if (Utils.isPrimaryKey(id)) {
if (meta.compositePK) {
throw ValidationError.invalidCompositeIdentifier(meta);
}
id = [id] as Primary<T>;
}
const entity = this.getEntityFactory().createReference<T>(entityName, id);
this.getUnitOfWork().merge(entity, [entity], false);
if (wrapped) {
return Reference.create(entity);
}
return entity;
}
/**
* Returns total number of entities matching your `where` query.
*/
async count<T>(entityName: EntityName<T>, where: FilterQuery<T> = {}, options: CountOptions<T> = {}): Promise<number> {
entityName = Utils.className(entityName);
where = QueryHelper.processWhere(where, entityName, this.metadata);
where = await this.applyFilters(entityName, where, options.filters ?? {}, 'read');
this.validator.validateParams(where);
return this.driver.count(entityName, where, this.transactionContext);
}
/**
* Tells the EntityManager to make an instance managed and persistent.
* The entity will be entered into the database at or before transaction commit or as a result of the flush operation.
*/
persist(entity: AnyEntity | Reference<AnyEntity> | (AnyEntity | Reference<AnyEntity>)[]): this {
const entities = Utils.asArray(entity);
for (const ent of entities) {
this.getUnitOfWork().persist(Reference.unwrapReference(ent));
}
return this;
}
/**
* Persists your entity immediately, flushing all not yet persisted changes to the database too.
* Equivalent to `em.persist(e).flush()`.
*/
async persistAndFlush(entity: AnyEntity | Reference<AnyEntity> | (AnyEntity | Reference<AnyEntity>)[]): Promise<void> {
await this.persist(entity).flush();
}
/**
* Tells the EntityManager to make an instance managed and persistent.
* The entity will be entered into the database at or before transaction commit or as a result of the flush operation.
*
* @deprecated use `persist()`
*/
persistLater(entity: AnyEntity | AnyEntity[]): void {
this.persist(entity);
}
/**
* Removes an entity instance. You can force flushing via second parameter.
* A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation.
*
* To remove entities by condition, use `em.nativeDelete()`.
*/
remove<T extends AnyEntity<T>>(entity: T | Reference<T> | (T | Reference<T>)[]): this {
const entities = Utils.asArray(entity, true);
for (const ent of entities) {
if (!Utils.isEntity(ent, true)) {
throw new Error(`You need to pass entity instance or reference to 'em.remove()'. To remove entities by condition, use 'em.nativeDelete()'.`);
}
this.getUnitOfWork().remove(Reference.unwrapReference(ent));
}
return this;
}
/**
* Removes an entity instance immediately, flushing all not yet persisted changes to the database too.
* Equivalent to `em.remove(e).flush()`
*/
async removeAndFlush(entity: AnyEntity | Reference<AnyEntity>): Promise<void> {
await this.remove(entity).flush();
}
/**
* Removes an entity instance.
* A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation.
*
* @deprecated use `remove()`
*/
removeLater(entity: AnyEntity): void {
this.remove(entity);
}
/**
* Flushes all changes to objects that have been queued up to now to the database.
* This effectively synchronizes the in-memory state of managed objects with the database.
*/
async flush(): Promise<void> {
await this.getUnitOfWork().commit();
}
/**
* Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.
*/
clear(): void {
this.getUnitOfWork().clear();
}
/**
* Checks whether given property can be populated on the entity.
*/
canPopulate<T>(entityName: EntityName<T>, property: string): boolean {
entityName = Utils.className(entityName);
const [p, ...parts] = property.split('.');
const props = this.metadata.get(entityName).properties;
const ret = p in props && (props[p].reference !== ReferenceType.SCALAR || props[p].lazy);
if (!ret) {
return false;
}
if (parts.length > 0) {
return this.canPopulate(props[p].type, parts.join('.'));
}
return ret;
}
async populate<T extends AnyEntity<T>, P extends string | keyof T | Populate<T>>(entities: T, populate: P, where?: FilterQuery<T>, orderBy?: QueryOrderMap, refresh?: boolean, validate?: boolean): Promise<Loaded<T, P>>;
async populate<T extends AnyEntity<T>, P extends string | keyof T | Populate<T>>(entities: T[], populate: P, where?: FilterQuery<T>, orderBy?: QueryOrderMap, refresh?: boolean, validate?: boolean): Promise<Loaded<T, P>[]>;
async populate<T extends AnyEntity<T>, P extends string | keyof T | Populate<T>>(entities: T | T[], populate: P, where?: FilterQuery<T>, orderBy?: QueryOrderMap, refresh?: boolean, validate?: boolean): Promise<Loaded<T, P> | Loaded<T, P>[]>;
async populate<T extends AnyEntity<T>, P extends string | keyof T | Populate<T>>(entities: T | T[], populate: P, where: FilterQuery<T> = {}, orderBy: QueryOrderMap = {}, refresh = false, validate = true): Promise<Loaded<T, P> | Loaded<T, P>[]> {
const entitiesArray = Utils.asArray(entities);
if (entitiesArray.length === 0) {
return entities as Loaded<T, P>[];
}
populate = Utils.isString(populate) ? Utils.asArray(populate) as unknown as P : populate;
const entityName = entitiesArray[0].constructor.name;
const preparedPopulate = this.preparePopulate<T>(entityName, populate as true);
await this.entityLoader.populate(entityName, entitiesArray, preparedPopulate, { where, orderBy, refresh, validate });
return entities as Loaded<T, P>[];
}
/**
* Returns new EntityManager instance with its own identity map
*
* @param clear do we want clear identity map? defaults to true
* @param useContext use request context? should be used only for top level request scope EM, defaults to false
*/
fork(clear = true, useContext = false): D[typeof EntityManagerType] {
const em = new (this.constructor as typeof EntityManager)(this.config, this.driver, this.metadata, useContext);
em.filters = { ...this.filters };
em.filterParams = Utils.copy(this.filterParams);
if (!clear) {
Object.values(this.getUnitOfWork().getIdentityMap()).forEach(entity => em.merge(entity));
}
return em;
}
/**
* Gets the UnitOfWork used by the EntityManager to coordinate operations.
*/
getUnitOfWork(): UnitOfWork {
const em = this.useContext ? (RequestContext.getEntityManager() || this) : this;
return em.unitOfWork;
}
/**
* Gets the EntityFactory used by the EntityManager.
*/
getEntityFactory(): EntityFactory {
const em = this.useContext ? (RequestContext.getEntityManager() || this) : this;
return em.entityFactory;
}
getEventManager(): EventManager {
return this.eventManager;
}
/**
* Checks whether this EntityManager is currently operating inside a database transaction.
*/
isInTransaction(): boolean {
return !!this.transactionContext;
}
/**
* Gets the transaction context (driver dependent object used to make sure queries are executed on same connection).
*/
getTransactionContext<T extends Transaction = Transaction>(): T | undefined {
return this.transactionContext as T;
}
/**
* Gets the MetadataStorage.
*/
getMetadata(): MetadataStorage {
return this.metadata;
}
private checkLockRequirements(mode: LockMode | undefined, meta: EntityMetadata): void {
if (!mode) {
return;
}
if (mode === LockMode.OPTIMISTIC && !meta.versionProperty) {
throw ValidationError.notVersioned(meta);
}
if ([LockMode.PESSIMISTIC_READ, LockMode.PESSIMISTIC_WRITE].includes(mode) && !this.isInTransaction()) {
throw ValidationError.transactionRequired();
}
}
private async lockAndPopulate<T, P extends Populate<T> = any>(entityName: string, entity: T, where: FilterQuery<T>, options: FindOneOptions<T>): Promise<Loaded<T, P>> {
if (options.lockMode === LockMode.OPTIMISTIC) {
await this.lock(entity, options.lockMode, options.lockVersion);
}
const preparedPopulate = this.preparePopulate(entityName, options.populate as string[], options.strategy);
await this.entityLoader.populate<T>(entityName, [entity], preparedPopulate, { ...options, where });
return entity as Loaded<T, P>;
}
private preparePopulate<T>(entityName: string, populate?: Populate<T>, strategy?: LoadStrategy): PopulateOptions<T>[] {
if (!populate) {
return [];
}
const meta = this.metadata.get(entityName);
if (Utils.isPlainObject(populate)) {
return this.preparePopulateObject(meta, populate as true, strategy);
}
if (Array.isArray(populate)) {
populate = (populate as string[]).map(field => {
if (Utils.isString(field)) {
return { field };
}
return field;
}) as unknown as Populate<T>;
}
const ret: PopulateOptions<T>[] = this.entityLoader.normalizePopulate<T>(entityName, populate as true);
return ret.map(field => {
field.strategy = strategy ?? field.strategy;
return field;
});
}
private preparePopulateObject<T>(meta: EntityMetadata<T>, populate: PopulateMap<T>, strategy?: LoadStrategy): PopulateOptions<T>[] {
return Object.keys(populate).map(field => {
const prop = meta.properties[field];
const fieldStrategy = strategy ?? (Utils.isString(populate[field]) ? populate[field] : prop.strategy);
if (populate[field] === true) {
return { field, strategy: fieldStrategy };
}
if (Utils.isPlainObject(populate[field])) {
const meta2 = this.metadata.get(prop!.type);
return { field, strategy: fieldStrategy, children: this.preparePopulateObject(meta2, populate[field], strategy) };
}
return { field, strategy: fieldStrategy };
});
}
[inspect.custom]() {
return `[EntityManager<${this.id}>]`;
}
}