Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bug with new nested where filters #8005

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 52 additions & 35 deletions src/query-builder/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -993,51 +993,68 @@ export abstract class QueryBuilder<Entity> {

if (metadata.hasRelationWithPropertyPath(path)) {
const relation = metadata.findRelationWithPropertyPath(path)!;
const isEntityTarget = relation.inverseEntityMetadata.target === entity[key].constructor;

// There's also cases where we don't want to return back all of the properties.
// These handles the situation where someone passes the model & we don't need to make
// a HUGE `where` to uniquely look up the entity.
const primaryColumns = relation.inverseEntityMetadata.primaryColumns;
const seenPrimaryColumns = new Set<string>();
for (const primaryColumn of primaryColumns) {
const entityValueMap = primaryColumn.getEntityValueMap(entity[key]);
for (const [columnName, value] of Object.entries(entityValueMap || {})) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about embedded entity primary keys? Is that a concern here?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure - happy to hand off this pr to you if its easier.

Otherwise please point me to docs and I can try to add a test case.

if (value) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is null a valid PK value? I know 0 is. So is an empty string. Is that something we should be handling here? Only checking for undefined instead?

seenPrimaryColumns.add(columnName);
} else {
break;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we know this inner one is invalid, we know they all are. Do we want to break further up?

}
}
}
const hasOnlyPrimaryKeys = primaryColumns.length > 0 && seenPrimaryColumns.size === Object.keys(entity[key]).length;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's only primary columns do we actually care if it hits the optimizations?

In theory, it would be the same either way, wouldn't it?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The update flow uses this method and fails if you pass contact.id vs contactId.
ex. #8005 (comment)
That's the reason I added the hasOnlyPrimaryKeys check back.


if (isEntityTarget || hasOnlyPrimaryKeys) {
// There's also cases where we don't want to return back all of the properties.
// These handles the situation where someone passes the model & we don't need to make
// a HUGE `where` to uniquely look up the entity.

// In the case of a *-to-one, there's only ever one possible entity on the other side
// so if the join columns are all defined we can return just the relation itself
// because it will fetch only the join columns and do the lookup.
if (relation.relationType === "one-to-one" || relation.relationType === "many-to-one") {
const joinColumns = relation.joinColumns
.map(j => j.referencedColumn)
.filter((j): j is ColumnMetadata => !!j);

const hasAllJoinColumns = joinColumns.length > 0 && joinColumns.every(
column => column.getEntityValue(entity[key], false)
);

if (hasAllJoinColumns) {
paths.push(path);
continue;
}
}

Comment on lines +1017 to +1034
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the hasOnlyPrimaryKeys actually apply here? Isn't it just in the case of an isEntityTarget?
Can this ever apply with hasOnlyPrimaryKeys?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe you're right and I can have this block only apply to isEntityTarget.

if (relation.relationType === "one-to-many" || relation.relationType === "many-to-many") {
throw new Error(`Cannot query across ${relation.relationType} for property ${path}`);
}
Comment on lines +1035 to +1037
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty sure this needs to remain outside the if (isEntityTarget || hasOnlyPrimaryKeys) { ... } block as it's unrelated to the shortcuts taken. We just do not currently support this kind of query at all.


// In the case of a *-to-one, there's only ever one possible entity on the other side
// so if the join columns are all defined we can return just the relation itself
// because it will fetch only the join columns and do the lookup.
if (relation.relationType === "one-to-one" || relation.relationType === "many-to-one") {
const joinColumns = relation.joinColumns
.map(j => j.referencedColumn)
.filter((j): j is ColumnMetadata => !!j);
// For any other case, if the `entity[key]` contains all of the primary keys we can do a
// lookup via these. We don't need to look up via any other values 'cause these are
// the unique primary keys.
// This handles the situation where someone passes the model & we don't need to make
// a HUGE where.

const hasAllJoinColumns = joinColumns.length > 0 && joinColumns.every(
const hasAllPrimaryKeys = primaryColumns.length > 0 && primaryColumns.every(
column => column.getEntityValue(entity[key], false)
);

if (hasAllJoinColumns) {
paths.push(path);
if (hasAllPrimaryKeys) {
const subPaths = primaryColumns.map(
column => `${path}.${column.propertyPath}`
);
paths.push(...subPaths);
continue;
}
}

if (relation.relationType === "one-to-many" || relation.relationType === "many-to-many") {
throw new Error(`Cannot query across ${relation.relationType} for property ${path}`);
}

// For any other case, if the `entity[key]` contains all of the primary keys we can do a
// lookup via these. We don't need to look up via any other values 'cause these are
// the unique primary keys.
// This handles the situation where someone passes the model & we don't need to make
// a HUGE where.
const primaryColumns = relation.inverseEntityMetadata.primaryColumns;
const hasAllPrimaryKeys = primaryColumns.length > 0 && primaryColumns.every(
column => column.getEntityValue(entity[key], false)
);

if (hasAllPrimaryKeys) {
const subPaths = primaryColumns.map(
column => `${path}.${column.propertyPath}`
);
paths.push(...subPaths);
continue;
}

// If nothing else, just return every property that's being passed to us.
const subPaths = this.createPropertyPath(relation.inverseEntityMetadata, entity[key])
.map(p => `${path}.${p}`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ async function createDotenvFiles() {
}

async function createYamlFiles() {
await fs.mkdir(path.join(__dirname, "configs/yaml"));
await fs.mkdir(path.join(__dirname, "configs/yaml"), { recursive: true });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this change needed?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wasn't able to run test-fast multiple times in a row. It would complain that the directory already existed.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a bigger problem that our tests have than just this. Can you omit this change for now just to simplify this PR & what it touches? If we have to revert or find the cause of something it makes it a whole lot easier if it's one PR for one change.

await fs.writeFile(path.join(__dirname, "configs/yaml/test-yaml.yaml"), "- type: \"sqlite\"\n name: \"file\"\n database: \"test-yaml\"");
}

Expand Down
82 changes: 60 additions & 22 deletions test/functional/query-builder/select/query-builder-select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,32 +219,45 @@ describe("query builder > select", () => {

describe("many-to-many", () => {
it("should craft query with exact value", () => Promise.all(connections.map(async connection => {
const [sql, params] = connection.createQueryBuilder(Post, "post")
.select("post.id")
.leftJoin("post.tags", "tags_join")
.where({
"tags": {
"name": "Foo"
}
})
.getQueryAndParameters();

expect(() => {
connection.createQueryBuilder(Post, "post")
.select("post.id")
.leftJoin("post.tags", "tags_join")
.where({
"tags": {
"name": "Foo"
}
})
.getQueryAndParameters();
}).to.throw();
expect(sql).to.equal(
'SELECT "post"."id" AS "post_id" FROM "post" "post" ' +
'LEFT JOIN "post_tags_tag" "post_tags_join" ON "post_tags_join"."postId"="post"."id" ' +
'LEFT JOIN "tag" "tags_join" ON "tags_join"."id"="post_tags_join"."tagId" ' +
'WHERE "tags_join"."name" = ?'
);

expect(params).to.eql(["Foo"]);
})));

it("should craft query with FindOperator", () => Promise.all(connections.map(async connection => {
expect(() => {
connection.createQueryBuilder(Post, "post")
.select("post.id")
.leftJoin("post.tags", "tags_join")
.where({
"tags": {
"name": IsNull()
}
})
.getQueryAndParameters();
}).to.throw();
const [sql, params] = connection.createQueryBuilder(Post, "post")
.select("post.id")
.leftJoin("post.tags", "tags_join")
.where({
"tags": {
"name": IsNull()
}
})
.getQueryAndParameters();

expect(sql).to.equal(
'SELECT "post"."id" AS "post_id" FROM "post" "post" ' +
'LEFT JOIN "post_tags_tag" "post_tags_join" ON "post_tags_join"."postId"="post"."id" ' +
'LEFT JOIN "tag" "tags_join" ON "tags_join"."id"="post_tags_join"."tagId" ' +
'WHERE "tags_join"."name" IS NULL'
);

expect(params).to.eql([]);
})));
});

Expand Down Expand Up @@ -342,6 +355,31 @@ describe("query builder > select", () => {

expect(params).to.eql(["Foo", "Bar", "Baz"]);
})));

it("should craft query with FindOperator with nested primary/non-primary key", () => Promise.all(connections.map(async connection => {
const [sql, params] = connection.createQueryBuilder(HeroImage, "hero")
.leftJoin("hero.post", "posts")
.leftJoin("posts.category", "category")
.where({
post: {
category: {
id: In([1, 2, 3]),
name: In(["Foo", "Bar", "Baz"]),
}
}
})
.getQueryAndParameters();

expect(sql).to.equal(
'SELECT "hero"."id" AS "hero_id", "hero"."url" AS "hero_url" ' +
'FROM "hero_image" "hero" ' +
'LEFT JOIN "post" "posts" ON "posts"."heroImageId"="hero"."id" ' +
'LEFT JOIN "category" "category" ON "category"."id"="posts"."categoryId" ' +
'WHERE ("category"."id" IN (?, ?, ?) AND "category"."name" IN (?, ?, ?))'
);

expect(params).to.eql([1, 2, 3, "Foo", "Bar", "Baz"]);
})));
});
});

Expand Down