Skip to content

Commit

Permalink
fix(core): allow setting values to null on unloaded references
Browse files Browse the repository at this point in the history
Closes #5274
  • Loading branch information
B4nan committed Mar 5, 2024
1 parent fa712ca commit 1cbead6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
13 changes: 11 additions & 2 deletions packages/core/src/unit-of-work/ChangeSetComputer.ts
Expand Up @@ -104,8 +104,17 @@ export class ChangeSetComputer {

private computePayload<T extends object>(entity: T, ignoreUndefined = false): EntityData<T> {
const data = this.comparator.prepareEntity(entity);
const entityName = helper(entity).__meta.className;
const originalEntityData = helper(entity).__originalEntityData;
const wrapped = helper(entity);
const entityName = wrapped.__meta.className;
const originalEntityData = wrapped.__originalEntityData;

if (!wrapped.__initialized) {
for (const prop of wrapped.__meta.primaryKeys) {
delete data[prop];
}

return data;
}

if (originalEntityData) {
const comparator = this.comparator.getEntityComparator(entityName);
Expand Down
18 changes: 18 additions & 0 deletions tests/EntityManager.postgre.test.ts
Expand Up @@ -1855,6 +1855,24 @@ describe('EntityManagerPostgre', () => {
expect(author.age).toBe(123);
});

test('update reference with null', async () => {
await orm.em.insertMany(Author2, [
{ id: 1, name: 'name', email: 'email1', age: 123 },
{ id: 2, name: 'name', email: 'email2', age: 1, favouriteAuthor: 1 },
]);
const ref2 = orm.em.getReference(Author2, 2);

const mock = mockLogger(orm, ['query', 'query-params']);
ref2.favouriteAuthor = null;
await orm.em.flush();

expect(mock.mock.calls[0][0]).toMatch('begin');
expect(mock.mock.calls[1][0]).toMatch(/update "author2" set "favourite_author_id" = NULL, "updated_at" = '.*' where "id" = 2/);
expect(mock.mock.calls[2][0]).toMatch('commit');

expect(ref2.favouriteAuthor).toBeNull();
});

test('update with raw sql fragment', async () => {
await orm.em.insertMany(Author2, [
{ id: 1, name: 'name', email: 'email1', age: 123 },
Expand Down
4 changes: 2 additions & 2 deletions tests/entities-sql/Author2.ts
Expand Up @@ -119,8 +119,8 @@ export class Author2 extends BaseEntity2 {
@ManyToOne({ nullable: true, updateRule: 'no action', deleteRule: 'cascade' })
favouriteBook?: Book2;

@ManyToOne({ nullable: true })
favouriteAuthor?: Author2;
@ManyToOne(() => Author2, { nullable: true })
favouriteAuthor?: Author2 | null;

@Embedded(() => Identity, { nullable: true, object: true })
identity?: Identity;
Expand Down

0 comments on commit 1cbead6

Please sign in to comment.