fix(db-postgres): count crashes when query contains subqueries and doesn't return any rows (#12273)
Fixes https://github.com/payloadcms/payload/issues/12264 Uses safe object access in `countDistinct`, fallbacks to `0`
This commit is contained in:
@@ -16,7 +16,7 @@ export const countDistinct: CountDistinct = async function countDistinct(
|
||||
})
|
||||
.from(this.tables[tableName])
|
||||
.where(where)
|
||||
return Number(countResult[0]?.count)
|
||||
return Number(countResult?.[0]?.count ?? 0)
|
||||
}
|
||||
|
||||
let query: SQLiteSelect = db
|
||||
@@ -39,5 +39,5 @@ export const countDistinct: CountDistinct = async function countDistinct(
|
||||
// Instead, COUNT (GROUP BY id) can be used which is still slower than COUNT(*) but acceptable.
|
||||
const countResult = await query
|
||||
|
||||
return Number(countResult[0]?.count)
|
||||
return Number(countResult?.[0]?.count ?? 0)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ export const countDistinct: CountDistinct = async function countDistinct(
|
||||
})
|
||||
.from(this.tables[tableName])
|
||||
.where(where)
|
||||
return Number(countResult[0].count)
|
||||
|
||||
return Number(countResult?.[0]?.count ?? 0)
|
||||
}
|
||||
|
||||
let query = db
|
||||
@@ -39,5 +40,5 @@ export const countDistinct: CountDistinct = async function countDistinct(
|
||||
// Instead, COUNT (GROUP BY id) can be used which is still slower than COUNT(*) but acceptable.
|
||||
const countResult = await query
|
||||
|
||||
return Number(countResult[0].count)
|
||||
return Number(countResult?.[0]?.count ?? 0)
|
||||
}
|
||||
|
||||
@@ -2451,4 +2451,37 @@ describe('database', () => {
|
||||
|
||||
expect(res.docs[0].id).toBe(customID.id)
|
||||
})
|
||||
|
||||
it('should count with a query that contains subqueries', async () => {
|
||||
const category = await payload.create({
|
||||
collection: 'categories',
|
||||
data: { title: 'new-category' },
|
||||
})
|
||||
const post = await payload.create({
|
||||
collection: 'posts',
|
||||
data: { title: 'new-post', category: category.id },
|
||||
})
|
||||
|
||||
const result_1 = await payload.count({
|
||||
collection: 'posts',
|
||||
where: {
|
||||
'category.title': {
|
||||
equals: 'new-category',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
expect(result_1.totalDocs).toBe(1)
|
||||
|
||||
const result_2 = await payload.count({
|
||||
collection: 'posts',
|
||||
where: {
|
||||
'category.title': {
|
||||
equals: 'non-existing-category',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
expect(result_2.totalDocs).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user