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:

Postgres 2 000 000 rows:

SQLite 400 000 rows:

SQLite 2 000 000 rows:

## 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
37 lines
908 B
TypeScript
37 lines
908 B
TypeScript
import type { ChainedMethods } from '@payloadcms/drizzle/types'
|
|
|
|
import { chainMethods } from '@payloadcms/drizzle'
|
|
import { count, sql } from 'drizzle-orm'
|
|
|
|
import type { CountDistinct, SQLiteAdapter } from './types.js'
|
|
|
|
export const countDistinct: CountDistinct = async function countDistinct(
|
|
this: SQLiteAdapter,
|
|
{ db, joins, tableName, where },
|
|
) {
|
|
const chainedMethods: ChainedMethods = []
|
|
|
|
joins.forEach(({ condition, table }) => {
|
|
chainedMethods.push({
|
|
args: [table, condition],
|
|
method: 'leftJoin',
|
|
})
|
|
})
|
|
|
|
const countResult = await chainMethods({
|
|
methods: chainedMethods,
|
|
query: db
|
|
.select({
|
|
count:
|
|
joins.length > 0
|
|
? sql`count
|
|
(DISTINCT ${this.tables[tableName].id})`.mapWith(Number)
|
|
: count(),
|
|
})
|
|
.from(this.tables[tableName])
|
|
.where(where),
|
|
})
|
|
|
|
return Number(countResult[0].count)
|
|
}
|