Skip to content

Commit

Permalink
fix(core): improve propagation of changes to 1:1 relations
Browse files Browse the repository at this point in the history
Related: #3614
  • Loading branch information
B4nan committed Oct 24, 2022
1 parent 710923a commit 389b4a2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions packages/core/src/entity/EntityHelper.ts
Expand Up @@ -185,6 +185,16 @@ export class EntityHelper {
private static propagateOneToOne<T extends object, O extends object>(entity: T, owner: O, prop: EntityProperty<O>, prop2: EntityProperty<T>, value?: T[keyof T & string], old?: T): void {
helper(entity).__pk = helper(entity).getPrimaryKey()!;

// the inverse side will be changed on the `value` too, so we need to clean-up and schedule orphan removal there too
if (value?.[prop2.name as string] != null && value?.[prop2.name as string] !== entity) {
const other = Reference.unwrapReference(value![prop2.name as string]);
delete helper(other).__data[prop.name];

if (prop2.orphanRemoval) {
helper(other).__em?.getUnitOfWork().scheduleOrphanRemoval(other);
}
}

if (value == null) {
entity[prop2.name] = value as T[keyof T & string];
} else if (prop2.mapToPk) {
Expand Down
18 changes: 18 additions & 0 deletions tests/issues/GH3614.test.ts
Expand Up @@ -121,3 +121,21 @@ test('change a 1:1 relation with a new entity and not delete the old one', async
const oldOwner2 = await orm.em.fork().findOne(User, oldOwner.id);
expect(oldOwner2).not.toBeNull();
});

test('change a 1:1 relation with a new entity and delete the old one', async () => {
const project = await createProject();
const oldOwner = project.owner!;
orm.em.create(User, { name: 'Johnny', project1: 1 });
expect(oldOwner.unwrap().project1).toBeUndefined();

const mock = mockLogger(orm, ['query']);
await orm.em.flush();
const queries = mock.mock.calls.map(q => q[0]);

expect(queries[1]).toMatch('delete from `user` where `id` in (?)');
expect(queries[2]).toMatch('insert into `user` (`name`, `project1_id`) values (?, ?)');

const oldOwner2 = await orm.em.fork().findOne(User, oldOwner.id);
expect(oldOwner2).toBeNull();
});

0 comments on commit 389b4a2

Please sign in to comment.