Skip to content

Commit

Permalink
fix count
Browse files Browse the repository at this point in the history
  • Loading branch information
zfben committed Feb 7, 2025
1 parent 13e93e9 commit c8bd82c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
13 changes: 12 additions & 1 deletion src/__tests__/query-builder/query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,11 +211,22 @@ describe('QueryBuilder/query', () => {
})

describe('count', () => {
it('counts the number of rows', async () => {
it('should work', async () => {
const result = await new QueryBuilder(client, 'query').count()

expect(result).toEqual(2)
})

it('work with where and ignore orderBy, limit and offset', async () => {
const result = await new QueryBuilder(client, 'query')
.where('name', 'Alice')
.orderBy('id')
.limit(1)
.offset(1)
.count()

expect(result).toEqual(1)
})
})

describe('first', () => {
Expand Down
2 changes: 2 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ export class Client {
let paramIndex = 0
const text = (query as string).replace(/\?/g, () => `$${++paramIndex}`)

console.log('raw', text, paramsArray)

return this.postgres.unsafe(text, paramsArray) as Promise<T[]>
}

Expand Down
14 changes: 9 additions & 5 deletions src/query-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,6 @@ export class QueryBuilder<
params.push(this.offsetValue)
}

console.log(sql.join(' '), params)

return {
sql: sql.join(' '),
params,
Expand All @@ -224,10 +222,16 @@ export class QueryBuilder<
}

async count() {
this.select('COUNT(*)' as any)
const sql = ['SELECT COUNT(*) AS count']
const params: any[] = []

const { sql, params } = this.toSql()
const result = await this.client.raw(sql, params)
sql.push('FROM', escapeIdentifier(this.table))

const { sql: whereSql, params: whereParams } = this.buildWhereSql()
sql.push(whereSql)
params.push(...whereParams)

const result = await this.client.raw(sql.join(' '), params)

return Number.parseInt(result[0].count, 10)
}
Expand Down

0 comments on commit c8bd82c

Please sign in to comment.