ForbesLindesay / atdatabases

TypeScript clients for databases that prevent SQL Injection
https://www.atdatabases.org
MIT License
609 stars 47 forks source link

Fix: Generic Type Support in 'Queryable.query' #306

Closed mustakimkr closed 10 months ago

mustakimkr commented 1 year ago

Issue:

This PR addresses issue #302, which reported that the query method in the @databases/pg library lacks support for generic types, unlike the pool.query method from the pg library.

Please review the proposed changes and provide feedback. This PR aims to improve type safety and developer experience when using the @databases/pg library by allowing users to specify the expected result types when executing SQL queries.

rollingversions[bot] commented 1 year ago

There is no change log for this pull request yet.

Create a changelog

ForbesLindesay commented 10 months ago

The result of running arbitrary SQL is always an array of unknown values. Adding generic type parameters introduces a false sense of security.

Instead of:

  const records = await db.query<{screen_name: string; age: number}>(
    sql`SELECT screen_name, age FROM ${table} ORDER BY screen_name ASC`,
  );

You should just write:

  const records: {screen_name: string; age: number}[] = await db.query(
    sql`SELECT screen_name, age FROM ${table} ORDER BY screen_name ASC`,
  );

or

  const records = await db.query(
    sql`SELECT screen_name, age FROM ${table} ORDER BY screen_name ASC`,
  ) as {screen_name: string; age: number}[];

It's nearly the exact same number of characters, and requires no changes to the library. I prefer this syntax as it makes it clearer that I'm not passing a generic type parameter to db.query that's then being checked in some way, I'm just running a query and then telling TypeScript what type the returned data has.