fix(db-sqlite): exists operator in createJSONQuery (#13907)

Fixes https://github.com/payloadcms/payload/issues/13882
This commit is contained in:
Sasha
2025-09-24 18:42:33 +03:00
committed by GitHub
parent 59414bd8f1
commit f980a86bd6
3 changed files with 93 additions and 5 deletions

View File

@@ -48,6 +48,39 @@ const createConstraint = ({
value,
}: CreateConstraintArgs): string => {
const newAlias = `${pathSegments[0]}_alias_${pathSegments.length - 1}`
if (operator === 'exists' && value === false) {
operator = 'not_exists'
value = true
} else if (operator === 'not_exists' && value === false) {
operator = 'exists'
value = true
}
if (operator === 'exists') {
if (pathSegments.length === 1) {
return `EXISTS (SELECT 1 FROM json_each("${pathSegments[0]}") AS ${newAlias})`
}
return `EXISTS (
SELECT 1
FROM json_each(${alias}.value -> '${pathSegments[0]}') AS ${newAlias}
WHERE ${newAlias}.key = '${pathSegments[1]}'
)`
}
if (operator === 'not_exists') {
if (pathSegments.length === 1) {
return `NOT EXISTS (SELECT 1 FROM json_each("${pathSegments[0]}") AS ${newAlias})`
}
return `NOT EXISTS (
SELECT 1
FROM json_each(${alias}.value -> '${pathSegments[0]}') AS ${newAlias}
WHERE ${newAlias}.key = '${pathSegments[1]}'
)`
}
let formattedValue = value
let formattedOperator = operator
if (['contains', 'like'].includes(operator)) {

View File

@@ -120,11 +120,6 @@ export const getFolderResultsComponentAndData = async ({
exists: false,
},
},
{
folderType: {
equals: null,
},
},
],
}
: undefined,

View File

@@ -406,6 +406,66 @@ describe('Joins Field', () => {
expect(findFolder?.docs[0]?.documentsAndFolders?.docs).toHaveLength(1)
})
it('should query where with exists for hasMany select fields', async () => {
await payload.delete({ collection: 'payload-folders', where: {} })
const folderDoc = await payload.create({
collection: 'payload-folders',
data: {
name: 'scopedFolder',
folderType: ['folderPoly1', 'folderPoly2'],
},
})
await payload.create({
collection: 'payload-folders',
data: {
name: 'childFolder',
folderType: ['folderPoly1'],
folder: folderDoc.id,
},
})
const findFolder = await payload.find({
collection: 'payload-folders',
where: {
id: {
equals: folderDoc.id,
},
},
joins: {
documentsAndFolders: {
limit: 100_000,
sort: 'name',
where: {
and: [
{
relationTo: {
equals: 'payload-folders',
},
},
{
or: [
{
folderType: {
in: ['folderPoly1'],
},
},
{
folderType: {
exists: false,
},
},
],
},
],
},
},
},
})
expect(findFolder?.docs[0]?.documentsAndFolders?.docs).toHaveLength(1)
})
it('should filter joins using where query', async () => {
const categoryWithPosts = await payload.findByID({
id: category.id,