Skip to content

Commit

Permalink
fix(query-builder): respect explicit entity schema
Browse files Browse the repository at this point in the history
Closes #2740
  • Loading branch information
B4nan committed Feb 11, 2022
1 parent a7fc7a1 commit 717aa5e
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 7 deletions.
2 changes: 1 addition & 1 deletion packages/knex/src/query/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class QueryBuilder<T extends AnyEntity<T> = AnyEntity> {

this.alias = alias ?? this.getNextAlias(this.entityName);
this._aliasMap[this.alias] = this.entityName;
this.helper = new QueryBuilderHelper(this.entityName, this.alias, this._aliasMap, this.subQueries, this.metadata, this.knex, this.platform);
this.helper = new QueryBuilderHelper(this.entityName, this.alias, this._aliasMap, this.subQueries, this.knex, this.driver);
}

select(fields: Field<T> | Field<T>[], distinct = false): SelectQueryBuilder<T> {
Expand Down
17 changes: 11 additions & 6 deletions packages/knex/src/query/QueryBuilderHelper.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
import type { Knex } from 'knex';
import { inspect } from 'util';
import type { Dictionary, EntityData, EntityMetadata, EntityProperty, FlatQueryOrderMap, MetadataStorage, Platform, QBFilterQuery } from '@mikro-orm/core';
import type { Dictionary, EntityData, EntityMetadata, EntityProperty, FlatQueryOrderMap, QBFilterQuery } from '@mikro-orm/core';
import { LockMode, OptimisticLockError, QueryOperator, QueryOrderNumeric, ReferenceType, Utils } from '@mikro-orm/core';
import { QueryType } from './enums';
import type { Field, JoinOptions } from '../typings';
import type { AbstractSqlDriver } from '../AbstractSqlDriver';

/**
* @internal
*/
export class QueryBuilderHelper {

private readonly platform = this.driver.getPlatform();
private readonly metadata = this.driver.getMetadata();

constructor(private readonly entityName: string,
private readonly alias: string,
private readonly aliasMap: Dictionary<string>,
private readonly subQueries: Dictionary<string>,
private readonly metadata: MetadataStorage,
private readonly knex: Knex,
private readonly platform: Platform) { }
private readonly driver: AbstractSqlDriver) { }

mapper(field: string, type?: QueryType): string;
mapper(field: string, type?: QueryType, value?: any, alias?: string | null): string;
Expand Down Expand Up @@ -139,15 +142,15 @@ export class QueryBuilderHelper {
}

joinOneToReference(prop: EntityProperty, ownerAlias: string, alias: string, type: 'leftJoin' | 'innerJoin' | 'pivotJoin', cond: Dictionary = {}): JoinOptions {
const meta = this.metadata.find(prop.type)!;
const prop2 = meta.properties[prop.mappedBy || prop.inversedBy];
const prop2 = prop.targetMeta!.properties[prop.mappedBy || prop.inversedBy];
const table = this.getTableName(prop.type);
const schema = this.driver.getSchemaName(prop.targetMeta);
const joinColumns = prop.owner ? prop.referencedColumnNames : prop2.joinColumns;
const inverseJoinColumns = prop.referencedColumnNames;
const primaryKeys = prop.owner ? prop.joinColumns : prop2.referencedColumnNames;

return {
prop, type, cond, ownerAlias, alias, table,
prop, type, cond, ownerAlias, alias, table, schema,
joinColumns, inverseJoinColumns, primaryKeys,
};
}
Expand All @@ -156,6 +159,7 @@ export class QueryBuilderHelper {
return {
prop, type, cond, ownerAlias, alias,
table: this.getTableName(prop.type),
schema: this.driver.getSchemaName(prop.targetMeta),
joinColumns: prop.referencedColumnNames,
primaryKeys: prop.fieldNames,
};
Expand All @@ -171,6 +175,7 @@ export class QueryBuilderHelper {
inverseJoinColumns: prop.inverseJoinColumns,
primaryKeys: prop.referencedColumnNames,
table: prop.pivotTable,
schema: this.driver.getSchemaName(this.metadata.find(prop.pivotTable)),
path: path.endsWith('[pivot]') ? path : `${path}[pivot]`,
} as JoinOptions,
};
Expand Down
59 changes: 59 additions & 0 deletions tests/features/multiple-schemas/GH2740.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Entity, ManyToOne, PrimaryKey, Property, MikroORM } from '@mikro-orm/core';
import type { PostgreSqlDriver } from '@mikro-orm/postgresql';

@Entity({
tableName: 'person',
schema: 'foo',
})
export class PersonEntity {

@PrimaryKey()
id!: number;

@Property()
name!: string;

}

@Entity({
tableName: 'task',
schema: 'bar',
})
export class TaskEntity {

@PrimaryKey()
id!: number;

@ManyToOne(() => PersonEntity)
person!: PersonEntity;

}

describe('GH #2740', () => {

let orm: MikroORM<PostgreSqlDriver>;

beforeAll(async () => {
orm = await MikroORM.init({
type: 'postgresql',
dbName: 'mikro_orm_test_gh_2740',
entities: [PersonEntity, TaskEntity],
});
await orm.getSchemaGenerator().ensureDatabase();
await orm.getSchemaGenerator().dropSchema();
await orm.getSchemaGenerator().createSchema();
});

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

it('should respect the defined schema in queries on relations', async () => {
const qb = orm.em.createQueryBuilder(TaskEntity).where({
person: { name: 'test' },
});

expect(qb.getQuery()).toBe(`select "t0".* from "bar"."task" as "t0" left join "foo"."person" as "p1" on "t0"."person_id" = "p1"."id" where "p1"."name" = $1`);
});

});

0 comments on commit 717aa5e

Please sign in to comment.