dyedgreen / deno-sqlite

Deno SQLite module
https://deno.land/x/sqlite
MIT License
409 stars 36 forks source link

[feature request] statement typescript types support [column: value] definitions #151

Closed andykais closed 3 years ago

andykais commented 3 years ago

a follow up to https://github.com/dyedgreen/deno-sqlite/issues/140, for the same reasons that it is useful to query for key value pairs of javascript objects, it would be useful to declare statement rows using key values. Plus defining columns could allow typescript access to be more complete. E.g.

const rows = db.prepareQuery<{ id: number; name: string }>.all('SELECT id, name FROM person')
rows[0].name // typescript knows this is of type `string`

Its possible that statements could support both tuple style and key:value style type definitions via some typescript type inference magic. Is there an interest in this feature?

dyedgreen commented 3 years ago

This already works! query/ queryEntries support type parameters for tuples/ records respectively. Prepare supports three optional type parameters for the returned tuple, record, as well as the expected query parameter tuple or record. Is that what you’re looking for? (I believe the deno doc could do a better job of marking type parameters 😅)

dyedgreen commented 3 years ago

(See https://github.com/dyedgreen/deno-sqlite/blob/5c57a9ecb8b3fc1cdcc3efcc1ca2feb63cc78616/src/db.ts#L173 for the type script signature)

andykais commented 3 years ago

hmm it might be. Could I see an example usage? Do I need to repeat type definitions? E.g.

type ValueOf<T> = T[keyof T];
type TableRow = { id: number; name: string }
const rows = db.prepareQuery<ValueOf<TableRow>, TableRow>.all('SELECT id, name FROM person')
dyedgreen commented 3 years ago

Yes, that's exactly how you'd use it. The tuple and record type are provided separately, to avoid relying on the order of record fields, and to allow more flexible use e.g. with a specific record type, but Array instead of a tuple, etc ...

andykais commented 3 years ago

hmm alright. I suppose theres a few cases where its difficult to know for certain if youre dealing with a keyed object vs a tuple without being explicit. Closing this issue as my use case is supported