Skip to content

Commit

Permalink
fix(core): don't alias formulas in update/delete queries
Browse files Browse the repository at this point in the history
Closes #5334
  • Loading branch information
B4nan committed Mar 14, 2024
1 parent 00239eb commit 9e35642
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/core/src/metadata/MetadataDiscovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1351,7 +1351,7 @@ export class MetadataDiscovery {
prop.targetMeta = meta2;

if (!prop.formula && prop.persist === false && [ReferenceKind.MANY_TO_ONE, ReferenceKind.ONE_TO_ONE].includes(prop.kind) && !prop.embedded) {
prop.formula = a => `${a}.${prop.fieldNames[0]}`;
prop.formula = a => `${a}.${this.platform.quoteIdentifier(prop.fieldNames[0])}`;
}
}

Expand Down
7 changes: 6 additions & 1 deletion packages/knex/src/query/QueryBuilderHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,13 @@ export class QueryBuilderHelper {
const alias2 = this.knex.ref(a).toString();
const aliased = this.knex.ref(prop.fieldNames[0]).toString();
const as = alias === null ? '' : ` as ${aliased}`;
let value = prop.formula(alias2);

return this.knex.raw(`${prop.formula(alias2)}${as}`);
if (!this.isTableNameAliasRequired(type)) {
value = value.replaceAll(alias2 + '.', '');
}

return this.knex.raw(`${value}${as}`);
}

if (prop?.hasConvertToJSValueSQL) {
Expand Down
49 changes: 49 additions & 0 deletions tests/issues/GH5334.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Collection, Entity, ManyToOne, MikroORM, OneToMany, PrimaryKey, Property } from '@mikro-orm/sqlite';

@Entity()
class EntityA {

@PrimaryKey()
id!: number;

@OneToMany(() => EntityB, 'a')
bs = new Collection<EntityB>(this);

}

@Entity()
class EntityB {

@PrimaryKey()
id!: number;

@Property()
test!: string;

@ManyToOne(() => EntityA, { name: 'id', persist: false })
a!: EntityA;

}

let orm: MikroORM;

beforeAll(async () => {
orm = await MikroORM.init({
dbName: ':memory:',
entities: [EntityA, EntityB],
});
await orm.schema.refreshDatabase();
});

afterAll(async () => {
await orm.close(true);
});

test('delete entity from persist false relation', async () => {
orm.em.create(EntityA, {
bs: [{ test: 'qwer' }, { test: 'asdf' }, { test: 'yxcv' }],
}, { persist: true });

await orm.em.flush();
await orm.em.nativeDelete(EntityB, { a: 1 });
});

0 comments on commit 9e35642

Please sign in to comment.