Skip to content

Commit

Permalink
feat(core): allow forking EM without clearing identity map
Browse files Browse the repository at this point in the history
With this one can easily run parallel branches that will have its own identity map (keeping the old entities present so flushing will work as expected).
  • Loading branch information
B4nan committed Apr 16, 2019
1 parent d9d71fe commit 5e4603c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/EntityManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,8 +288,14 @@ export class EntityManager {
return ret;
}

fork(): EntityManager {
return new EntityManager(this.config, this.driver);
fork(clear = true): EntityManager {
const em = new EntityManager(this.config, this.driver);

if (!clear) {
Object.values(this.getUnitOfWork().getIdentityMap()).forEach(entity => em.merge(entity));
}

return em;
}

getUnitOfWork(): UnitOfWork {
Expand Down
16 changes: 16 additions & 0 deletions tests/EntityManager.mysql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,22 @@ describe('EntityManagerMySql', () => {
expect(b1.toJSON()).toMatchObject({ fooBar: b1.id });
});

test('persisting entities in parallel inside forked EM with copied IM', async () => {
const author = new Author2('name', 'email');
await orm.em.persistAndFlush(author); // we need to flush here so the entity gets inside IM

// fork EM without clearing the IM (once for each process), so author entity will be there
await Promise.all([
orm.em.fork(false).persistAndFlush(new Book2('b1', author)),
orm.em.fork(false).persistAndFlush(new Book2('b2', author)),
orm.em.fork(false).persistAndFlush(new Book2('b3', author)),
]);

orm.em.clear();
const a1 = (await orm.em.findOne(Author2, author.id, { populate: ['books'] }))!;
expect(a1.books.count()).toBe(3);
});

test('EM supports smart search conditions', async () => {
const author = new Author2('name', 'email');
const b1 = new Book2('b1', author);
Expand Down

0 comments on commit 5e4603c

Please sign in to comment.