Skip to content

Commit

Permalink
fix(core): support self referencing with Reference wrapper
Browse files Browse the repository at this point in the history
Closes #610
  • Loading branch information
B4nan committed Aug 9, 2020
1 parent ac9b814 commit fd1e158
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/core/src/unit-of-work/UnitOfWork.ts
Expand Up @@ -256,7 +256,7 @@ export class UnitOfWork {
.filter(prop => (prop.reference === ReferenceType.ONE_TO_ONE && prop.owner) || prop.reference === ReferenceType.MANY_TO_ONE)
.filter(prop => changeSet.entity[prop.name])
.forEach(prop => {
const cs = this.changeSets.find(cs => cs.entity === changeSet.entity[prop.name]);
const cs = this.changeSets.find(cs => cs.entity === Utils.unwrapReference(changeSet.entity[prop.name]));
const isScheduledForInsert = cs && cs.type === ChangeSetType.CREATE && !cs.persisted;

if (isScheduledForInsert) {
Expand Down
56 changes: 56 additions & 0 deletions tests/issues/GH610.test.ts
@@ -0,0 +1,56 @@
import { unlinkSync } from 'fs';
import { Entity, PrimaryKey, ManyToOne, IdentifiedReference, Property, MikroORM, wrap, Logger } from '@mikro-orm/core';
import { AbstractSqlDriver, SchemaGenerator } from '@mikro-orm/knex';
import { BASE_DIR } from '../bootstrap';

@Entity()
export class Test {

@PrimaryKey()
id!: number;

@Property()
name!: string;

@ManyToOne(() => Test, { nullable: true, wrappedReference: true })
rootNode?: IdentifiedReference<Test>;

}

describe('GH issue 610', () => {

let orm: MikroORM<AbstractSqlDriver>;

beforeAll(async () => {
orm = await MikroORM.init({
entities: [Test],
dbName: BASE_DIR + '/../temp/mikro_orm_test_gh222.db',
type: 'sqlite',
highlight: false,
});
await new SchemaGenerator(orm.em).dropSchema();
await new SchemaGenerator(orm.em).createSchema();
});

afterAll(async () => {
await orm.close(true);
unlinkSync(orm.config.get('dbName')!);
});

test(`self referencing with Reference wrapper`, async () => {
const test = new Test();
test.name = 'hello';
test.rootNode = wrap(test).toReference();
orm.em.persist(test);

const mock = jest.fn();
const logger = new Logger(mock, true);
Object.assign(orm.config, { logger });
await orm.em.flush();
expect(mock.mock.calls[0][0]).toMatch('begin');
expect(mock.mock.calls[1][0]).toMatch('insert into `test` (`name`) values (?)');
expect(mock.mock.calls[2][0]).toMatch('update `test` set `root_node_id` = ? where `id` = ?');
expect(mock.mock.calls[3][0]).toMatch('commit');
});

});

0 comments on commit fd1e158

Please sign in to comment.