Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve support for multiple results #3121

Open
ViktorQvarfordt opened this issue Jan 5, 2024 · 0 comments
Open

Improve support for multiple results #3121

ViktorQvarfordt opened this issue Jan 5, 2024 · 0 comments

Comments

@ViktorQvarfordt
Copy link

The return type from pool.query (or client.query) is QueryResult, which is incorrect when multiple statements are executed. In that case the type is QueryResult[].

Example showing the problem:

import pg from 'pg'

// docker run --rm -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:15-alpine
const pool = new pg.Pool({ connectionString: 'postgresql://postgres:postgres@localhost:5432/postgres' })

const results = await pool.query(`
  SELECT 1;
  SELECT 2;
`)

console.log(results[1].rows) // TS ERROR: 'QueryResult<any>' cannot be indexed. It is not an array.

But the code runs as expected.

I think this pattern of making the object an array or an object is not so good. The correct type right now is QueryResult | QueryResult[] which is difficult to work with since one would need to check if (Array.isArray(result)) each type to do type narrowing.

I suggest that we make the following (mostly) backwards compatible change: Change the return type of query to QueryResult & QueryResult[]. It may look strange but it is fully doable in both javascript and typescript; an array that also has object properties.

Proof of concept code:

type SingleQueryResult = { rows: string[] }

type QueryResult = SingleQueryResult & SingleQueryResult[]

const mockResult0 = { rows: ['result-0-row-0'] }
const mockResult1 = { rows: ['result-1-row-0'] }
const mockResult: QueryResult = Object.assign([mockResult0, mockResult1], mockResult0)

const resultDefault = mockResult
const result1 = mockResult[1]
console.log(resultDefault.rows[0] === 'result-0-row-0' && result1?.rows[0] === 'result-1-row-0') // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant