Skip to content

Commit

Permalink
Merge pull request #14795 from Budibase/chore/negated-join-filters
Browse files Browse the repository at this point in the history
Fix negated join filters on relationships
  • Loading branch information
adrinr authored Oct 17, 2024
2 parents a5e0a71 + 0f43c8f commit 6ccf8ee
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 30 deletions.
81 changes: 60 additions & 21 deletions packages/backend-core/src/sql/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@ import {
InternalSearchFilterOperator,
JsonFieldMetadata,
JsonTypes,
LogicalOperator,
Operation,
prefixed,
QueryJson,
QueryOptions,
RangeOperator,
RelationshipsJson,
SearchFilterKey,
SearchFilters,
SortOrder,
SqlClient,
Expand Down Expand Up @@ -96,6 +98,22 @@ function isSqs(table: Table): boolean {
)
}

const allowEmptyRelationships: Record<SearchFilterKey, boolean> = {
[BasicOperator.EQUAL]: false,
[BasicOperator.NOT_EQUAL]: true,
[BasicOperator.EMPTY]: false,
[BasicOperator.NOT_EMPTY]: true,
[BasicOperator.FUZZY]: false,
[BasicOperator.STRING]: false,
[RangeOperator.RANGE]: false,
[ArrayOperator.CONTAINS]: false,
[ArrayOperator.NOT_CONTAINS]: true,
[ArrayOperator.CONTAINS_ANY]: false,
[ArrayOperator.ONE_OF]: false,
[LogicalOperator.AND]: false,
[LogicalOperator.OR]: false,
}

class InternalBuilder {
private readonly client: SqlClient
private readonly query: QueryJson
Expand Down Expand Up @@ -405,6 +423,7 @@ class InternalBuilder {

addRelationshipForFilter(
query: Knex.QueryBuilder,
allowEmptyRelationships: boolean,
filterKey: string,
whereCb: (filterKey: string, query: Knex.QueryBuilder) => Knex.QueryBuilder
): Knex.QueryBuilder {
Expand All @@ -430,9 +449,10 @@ class InternalBuilder {
relationship.to &&
relationship.tableName
) {
let subQuery = mainKnex
const joinTable = mainKnex
.select(mainKnex.raw(1))
.from({ [toAlias]: relatedTableName })
let subQuery = joinTable.clone()
const manyToMany = validateManyToMany(relationship)
let updatedKey

Expand All @@ -455,7 +475,6 @@ class InternalBuilder {
subQuery = subQuery
// add a join through the junction table
.innerJoin(throughTable, function () {
// @ts-ignore
this.on(
`${toAlias}.${manyToMany.toPrimary}`,
"=",
Expand All @@ -475,17 +494,38 @@ class InternalBuilder {
if (this.client === SqlClient.SQL_LITE) {
subQuery = this.addJoinFieldCheck(subQuery, manyToMany)
}

query = query.where(q => {
q.whereExists(whereCb(updatedKey, subQuery))
if (allowEmptyRelationships) {
q.orWhereNotExists(
joinTable.clone().innerJoin(throughTable, function () {
this.on(
`${fromAlias}.${manyToMany.fromPrimary}`,
"=",
`${throughAlias}.${manyToMany.from}`
)
})
)
}
})
} else {
const toKey = `${toAlias}.${relationship.to}`
const foreignKey = `${fromAlias}.${relationship.from}`
// "join" to the main table, making sure the ID matches that of the main
subQuery = subQuery.where(
`${toAlias}.${relationship.to}`,
toKey,
"=",
mainKnex.raw(
this.quotedIdentifier(`${fromAlias}.${relationship.from}`)
)
mainKnex.raw(this.quotedIdentifier(foreignKey))
)

query = query.where(q => {
q.whereExists(whereCb(updatedKey, subQuery.clone()))
if (allowEmptyRelationships) {
q.orWhereNotExists(subQuery)
}
})
}
query = query.whereExists(whereCb(updatedKey, subQuery))
}
}
return query
Expand Down Expand Up @@ -516,6 +556,7 @@ class InternalBuilder {
}
function iterate(
structure: AnySearchFilter,
operation: SearchFilterKey,
fn: (
query: Knex.QueryBuilder,
key: string,
Expand Down Expand Up @@ -574,6 +615,7 @@ class InternalBuilder {
}
query = builder.addRelationshipForFilter(
query,
allowEmptyRelationships[operation],
updatedKey,
(updatedKey, q) => {
return handleRelationship(q, updatedKey, value)
Expand Down Expand Up @@ -610,7 +652,7 @@ class InternalBuilder {
return `[${value.join(",")}]`
}
if (this.client === SqlClient.POSTGRES) {
iterate(mode, (q, key, value) => {
iterate(mode, ArrayOperator.CONTAINS, (q, key, value) => {
const wrap = any ? "" : "'"
const op = any ? "\\?| array" : "@>"
const fieldNames = key.split(/\./g)
Expand All @@ -628,7 +670,7 @@ class InternalBuilder {
this.client === SqlClient.MARIADB
) {
const jsonFnc = any ? "JSON_OVERLAPS" : "JSON_CONTAINS"
iterate(mode, (q, key, value) => {
iterate(mode, ArrayOperator.CONTAINS, (q, key, value) => {
return q[rawFnc](
`${not}COALESCE(${jsonFnc}(${key}, '${stringifyArray(
value
Expand All @@ -637,7 +679,7 @@ class InternalBuilder {
})
} else {
const andOr = mode === filters?.containsAny ? " OR " : " AND "
iterate(mode, (q, key, value) => {
iterate(mode, ArrayOperator.CONTAINS, (q, key, value) => {
let statement = ""
const identifier = this.quotedIdentifier(key)
for (let i in value) {
Expand Down Expand Up @@ -691,6 +733,7 @@ class InternalBuilder {
const fnc = allOr ? "orWhereIn" : "whereIn"
iterate(
filters.oneOf,
ArrayOperator.ONE_OF,
(q, key: string, array) => {
if (this.client === SqlClient.ORACLE) {
key = this.convertClobs(key)
Expand All @@ -715,7 +758,7 @@ class InternalBuilder {
)
}
if (filters.string) {
iterate(filters.string, (q, key, value) => {
iterate(filters.string, BasicOperator.STRING, (q, key, value) => {
const fnc = allOr ? "orWhere" : "where"
// postgres supports ilike, nothing else does
if (this.client === SqlClient.POSTGRES) {
Expand All @@ -730,10 +773,10 @@ class InternalBuilder {
})
}
if (filters.fuzzy) {
iterate(filters.fuzzy, like)
iterate(filters.fuzzy, BasicOperator.FUZZY, like)
}
if (filters.range) {
iterate(filters.range, (q, key, value) => {
iterate(filters.range, RangeOperator.RANGE, (q, key, value) => {
const isEmptyObject = (val: any) => {
return (
val &&
Expand Down Expand Up @@ -799,7 +842,7 @@ class InternalBuilder {
})
}
if (filters.equal) {
iterate(filters.equal, (q, key, value) => {
iterate(filters.equal, BasicOperator.EQUAL, (q, key, value) => {
const fnc = allOr ? "orWhereRaw" : "whereRaw"
if (this.client === SqlClient.MS_SQL) {
return q[fnc](
Expand All @@ -819,7 +862,7 @@ class InternalBuilder {
})
}
if (filters.notEqual) {
iterate(filters.notEqual, (q, key, value) => {
iterate(filters.notEqual, BasicOperator.NOT_EQUAL, (q, key, value) => {
const fnc = allOr ? "orWhereRaw" : "whereRaw"
if (this.client === SqlClient.MS_SQL) {
return q[fnc](
Expand All @@ -840,13 +883,13 @@ class InternalBuilder {
})
}
if (filters.empty) {
iterate(filters.empty, (q, key) => {
iterate(filters.empty, BasicOperator.EMPTY, (q, key) => {
const fnc = allOr ? "orWhereNull" : "whereNull"
return q[fnc](key)
})
}
if (filters.notEmpty) {
iterate(filters.notEmpty, (q, key) => {
iterate(filters.notEmpty, BasicOperator.NOT_EMPTY, (q, key) => {
const fnc = allOr ? "orWhereNotNull" : "whereNotNull"
return q[fnc](key)
})
Expand Down Expand Up @@ -1242,12 +1285,10 @@ class InternalBuilder {
})
: undefined
if (!throughTable) {
// @ts-ignore
query = query.leftJoin(toTableWithSchema, function () {
for (let relationship of columns) {
const from = relationship.from,
to = relationship.to
// @ts-ignore
this.orOn(`${fromAlias}.${from}`, "=", `${toAlias}.${to}`)
}
})
Expand All @@ -1258,7 +1299,6 @@ class InternalBuilder {
for (let relationship of columns) {
const fromPrimary = relationship.fromPrimary
const from = relationship.from
// @ts-ignore
this.orOn(
`${fromAlias}.${fromPrimary}`,
"=",
Expand All @@ -1270,7 +1310,6 @@ class InternalBuilder {
for (let relationship of columns) {
const toPrimary = relationship.toPrimary
const to = relationship.to
// @ts-ignore
this.orOn(`${toAlias}.${toPrimary}`, `${throughAlias}.${to}`)
}
})
Expand Down
26 changes: 19 additions & 7 deletions packages/server/src/api/routes/tests/search.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2384,7 +2384,10 @@ describe.each([
],
},
}).toContainExactly([
{ name: "foo", productCat: [{ _id: productCatRows[0]._id }] },
{
name: "foo",
productCat: [{ _id: productCatRows[0]._id }],
},
])
}
)
Expand Down Expand Up @@ -2462,7 +2465,7 @@ describe.each([
}).toContainExactly([
{ name: "foo", productCat: [{ _id: productCatRows[0]._id }] },
{ name: "bar", productCat: [{ _id: productCatRows[1]._id }] },
// { name: "baz", productCat: undefined }, // TODO
{ name: "baz", productCat: undefined },
])
})

Expand All @@ -2484,7 +2487,10 @@ describe.each([
],
},
}).toContainExactly([
{ name: "foo", productCat: [{ _id: productCatRows[0]._id }] },
{
name: "foo",
productCat: [{ _id: productCatRows[0]._id }],
},
])
}
)
Expand All @@ -2508,9 +2514,15 @@ describe.each([
],
},
}).toContainExactly([
{ name: "foo", productCat: [{ _id: productCatRows[0]._id }] },
{ name: "bar", productCat: [{ _id: productCatRows[1]._id }] },
// { name: "baz", productCat: undefined }, // TODO
{
name: "foo",
productCat: [{ _id: productCatRows[0]._id }],
},
{
name: "bar",
productCat: [{ _id: productCatRows[1]._id }],
},
{ name: "baz", productCat: undefined },
])
}
)
Expand All @@ -2534,7 +2546,7 @@ describe.each([
}).toContainExactly([
{ name: "foo", productCat: [{ _id: productCatRows[0]._id }] },
{ name: "bar", productCat: [{ _id: productCatRows[1]._id }] },
// { name: "baz", productCat: undefined }, // TODO
{ name: "baz", productCat: undefined },
])
})
})
Expand Down
4 changes: 2 additions & 2 deletions packages/server/src/integrations/tests/sqlAlias.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ describe("Captures of real examples", () => {
bindings: ["assembling", primaryLimit, relationshipLimit],
sql: expect.stringContaining(
multiline(
`where exists (select 1 from "tasks" as "b" inner join "products_tasks" as "c" on "b"."taskid" = "c"."taskid" where "c"."productid" = "a"."productid" and (COALESCE("b"."taskname" = $1, FALSE))`
`where (exists (select 1 from "tasks" as "b" inner join "products_tasks" as "c" on "b"."taskid" = "c"."taskid" where "c"."productid" = "a"."productid" and (COALESCE("b"."taskname" = $1, FALSE)))`
)
),
})
Expand Down Expand Up @@ -145,7 +145,7 @@ describe("Captures of real examples", () => {
],
sql: expect.stringContaining(
multiline(
`where exists (select 1 from "persons" as "c" where "c"."personid" = "a"."executorid" and ("c"."year" between $1 and $2)) and exists (select 1 from "persons" as "c" where "c"."personid" = "a"."qaid" and ("c"."year" between $3 and $4)) and exists (select 1 from "products" as "b" inner join "products_tasks" as "d" on "b"."productid" = "d"."productid" where "d"."taskid" = "a"."taskid" and (COALESCE("b"."productname" = $5, FALSE))`
`where (exists (select 1 from "persons" as "c" where "c"."personid" = "a"."executorid" and ("c"."year" between $1 and $2))) and (exists (select 1 from "persons" as "c" where "c"."personid" = "a"."qaid" and ("c"."year" between $3 and $4))) and (exists (select 1 from "products" as "b" inner join "products_tasks" as "d" on "b"."productid" = "d"."productid" where "d"."taskid" = "a"."taskid" and (COALESCE("b"."productname" = $5, FALSE))))`
)
),
})
Expand Down

0 comments on commit 6ccf8ee

Please sign in to comment.