Skip to content

Commit

Permalink
fix(core): ensure entity is not in persist stack after `em.insert/Man…
Browse files Browse the repository at this point in the history
…y()` is called

Closes #4692
  • Loading branch information
B4nan committed Sep 12, 2023
1 parent f6e8204 commit 94eed5e
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/core/src/EntityManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1090,6 +1090,9 @@ export class EntityManager<D extends IDatabaseDriver = IDatabaseDriver> {
}

if (Utils.isEntity<Entity>(data)) {
// the entity might have been created via `em.create()`, which adds it to the persist stack automatically
em.unitOfWork.getPersistStack().delete(data);

const meta = helper(data).__meta;
const payload = em.comparator.prepareEntity(data);
const cs = new ChangeSet(data, ChangeSetType.CREATE, payload, meta);
Expand Down Expand Up @@ -1127,6 +1130,9 @@ export class EntityManager<D extends IDatabaseDriver = IDatabaseDriver> {
if (Utils.isEntity<Entity>(data[0])) {
const meta = helper<Entity>(data[0]).__meta;
const css = data.map(row => {
// the entity might have been created via `em.create()`, which adds it to the persist stack automatically
em.unitOfWork.getPersistStack().delete(row);

const payload = em.comparator.prepareEntity(row) as EntityData<Entity>;
return new ChangeSet<Entity>(row as Entity, ChangeSetType.CREATE, payload, meta);
});
Expand Down
53 changes: 53 additions & 0 deletions tests/issues/__snapshots__/GH4692.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Entity, PrimaryKey, Property, Unique } from '@mikro-orm/core';
import { MikroORM } from '@mikro-orm/mysql';

@Entity()
@Unique({ properties: ['uniq1', 'uniq2'] })
class MyEntity1 {

@PrimaryKey()
id?: number;

@Property()
uniq1!: number;

@Property()
uniq2!: number;

@Property()
name!: string;

}

let orm: MikroORM;

beforeAll(async () => {
orm = await MikroORM.init({
dbName: 'mikro_4153',
port: 3308,
entities: [MyEntity1],
});
await orm.schema.refreshDatabase();
});

afterAll(() => orm.close(true));
beforeEach(() => orm.schema.clearDatabase());

test('4692', async () => {
const entities = [
orm.em.create(MyEntity1, { id: 1, uniq1: 1, uniq2: 1, name: 'first' }),
orm.em.create(MyEntity1, { id: 2, uniq1: 2, uniq2: 1, name: 'second' }),
];
await orm.em.insertMany(entities);

const res = await orm.em.find(MyEntity1, {});
expect(res).toHaveLength(2);
});

test('4692', async () => {
const entity = orm.em.create(MyEntity1, { id: 3, uniq1: 3, uniq2: 3, name: 'third' });
await orm.em.insert(entity);

const res = await orm.em.find(MyEntity1, {});
expect(res).toHaveLength(1);
});

0 comments on commit 94eed5e

Please sign in to comment.