fix(drizzle): optimize count querying when no joins (#7749)

Closes https://github.com/payloadcms/payload/issues/6321


To run benchmark:
`git checkout b840222` - from r1tsuu/payload
b840222784
`pnpm dev:postgres _community`

Benchmark results: (Before / After)
Postgres 400 000 rows:

![image](https://github.com/user-attachments/assets/cd7c478f-2057-4c7c-adec-5dbf0b05ec7b)
Postgres 2 000 000 rows:

![image](https://github.com/user-attachments/assets/04224f95-77eb-42ab-9591-887b197c597a)

SQLite 400 000 rows:

![image](https://github.com/user-attachments/assets/ba7482c2-30f1-4498-892d-59710639a7b3)
SQLite 2 000 000 rows:

![image](https://github.com/user-attachments/assets/c0a889f8-8e21-4b98-ac92-65ac735b8b32)



## Description

<!-- Please include a summary of the pull request and any related issues
it fixes. Please also include relevant motivation and context. -->

- [x] I have read and understand the
[CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md)
document in this repository.

## Type of change

<!-- Please delete options that are not relevant. -->


- [x] Bug fix (non-breaking change which fixes an issue)

## Checklist:

- [x] Existing test suite passes locally with my changes - See
https://github.com/payloadcms/payload/pull/7749#issuecomment-2295763721
This commit is contained in:
Sasha
2024-09-16 23:21:06 +03:00
committed by GitHub
parent b7a0b15786
commit 8520fd9570
2 changed files with 12 additions and 6 deletions

View File

@@ -1,7 +1,7 @@
import type { ChainedMethods } from '@payloadcms/drizzle/types'
import { chainMethods } from '@payloadcms/drizzle'
import { sql } from 'drizzle-orm'
import { count, sql } from 'drizzle-orm'
import type { CountDistinct, SQLiteAdapter } from './types.js'
@@ -22,8 +22,11 @@ export const countDistinct: CountDistinct = async function countDistinct(
methods: chainedMethods,
query: db
.select({
count: sql<number>`count
(DISTINCT ${this.tables[tableName].id})`,
count:
joins.length > 0
? sql`count
(DISTINCT ${this.tables[tableName].id})`.mapWith(Number)
: count(),
})
.from(this.tables[tableName])
.where(where),

View File

@@ -1,4 +1,4 @@
import { sql } from 'drizzle-orm'
import { count, sql } from 'drizzle-orm'
import type { ChainedMethods, TransactionPg } from '../types.js'
import type { BasePostgresAdapter, CountDistinct } from './types.js'
@@ -22,8 +22,11 @@ export const countDistinct: CountDistinct = async function countDistinct(
methods: chainedMethods,
query: (db as TransactionPg)
.select({
count: sql<string>`count
(DISTINCT ${this.tables[tableName].id})`,
count:
joins.length > 0
? sql`count
(DISTINCT ${this.tables[tableName].id})`.mapWith(Number)
: count(),
})
.from(this.tables[tableName])
.where(where),