Skip to content

Commit 4a56597

Browse files
authored
fix(db-postgres): count crashes when query contains subqueries and doesn't return any rows (#12273)
Fixes #12264 Uses safe object access in `countDistinct`, fallbacks to `0`
1 parent 27d644f commit 4a56597

File tree

3 files changed

+38
-4
lines changed

3 files changed

+38
-4
lines changed

packages/db-sqlite/src/countDistinct.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export const countDistinct: CountDistinct = async function countDistinct(
1616
})
1717
.from(this.tables[tableName])
1818
.where(where)
19-
return Number(countResult[0]?.count)
19+
return Number(countResult?.[0]?.count ?? 0)
2020
}
2121

2222
let query: SQLiteSelect = db
@@ -39,5 +39,5 @@ export const countDistinct: CountDistinct = async function countDistinct(
3939
// Instead, COUNT (GROUP BY id) can be used which is still slower than COUNT(*) but acceptable.
4040
const countResult = await query
4141

42-
return Number(countResult[0]?.count)
42+
return Number(countResult?.[0]?.count ?? 0)
4343
}

packages/drizzle/src/postgres/countDistinct.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ export const countDistinct: CountDistinct = async function countDistinct(
1616
})
1717
.from(this.tables[tableName])
1818
.where(where)
19-
return Number(countResult[0].count)
19+
20+
return Number(countResult?.[0]?.count ?? 0)
2021
}
2122

2223
let query = db
@@ -39,5 +40,5 @@ export const countDistinct: CountDistinct = async function countDistinct(
3940
// Instead, COUNT (GROUP BY id) can be used which is still slower than COUNT(*) but acceptable.
4041
const countResult = await query
4142

42-
return Number(countResult[0].count)
43+
return Number(countResult?.[0]?.count ?? 0)
4344
}

test/database/int.spec.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2451,4 +2451,37 @@ describe('database', () => {
24512451

24522452
expect(res.docs[0].id).toBe(customID.id)
24532453
})
2454+
2455+
it('should count with a query that contains subqueries', async () => {
2456+
const category = await payload.create({
2457+
collection: 'categories',
2458+
data: { title: 'new-category' },
2459+
})
2460+
const post = await payload.create({
2461+
collection: 'posts',
2462+
data: { title: 'new-post', category: category.id },
2463+
})
2464+
2465+
const result_1 = await payload.count({
2466+
collection: 'posts',
2467+
where: {
2468+
'category.title': {
2469+
equals: 'new-category',
2470+
},
2471+
},
2472+
})
2473+
2474+
expect(result_1.totalDocs).toBe(1)
2475+
2476+
const result_2 = await payload.count({
2477+
collection: 'posts',
2478+
where: {
2479+
'category.title': {
2480+
equals: 'non-existing-category',
2481+
},
2482+
},
2483+
})
2484+
2485+
expect(result_2.totalDocs).toBe(0)
2486+
})
24542487
})

0 commit comments

Comments
 (0)