Replies: 5 comments 1 reply
-
In particular I would love this to be as efficient as possible as I want to use this to add dynamic typescript to it. I don't know how the describe works internally or if that information is there anyways so it would have no overhead. |
Beta Was this translation helpful? Give feedback.
-
The query instance is not meant to be reused / reissued, but I can see why that would be expected, so it'd be interesting to think about |
Beta Was this translation helpful? Give feedback.
-
Yeah, I'm not sure it's a breaking change as much as uncharted territory, but that's also why I moved it to discussions since I'm not sure if it's a good idea or if it would see much usage yet. |
Beta Was this translation helpful? Give feedback.
-
import { deepStrictEqual } from "assert";
import { sql } from "./database.js";
const description = {
types: [ 23, 16 ],
columns: {
id: 23,
username: 1043,
openid_id: 1043,
password_hash: 1043,
type: 17425,
project_leader_id: 23,
group: 1043,
age: 23,
away: 16,
password_changed: 16,
force_in_project_id: 23,
computed_in_project_id: 23,
deleted: 16,
last_updated_by: 23
}
} as const;
export function typedSql<Q extends readonly number[], R extends { [column: string]: number }>(description: { types: Q; columns: R }) {
return async (template: TemplateStringsArray, ...args: DescriptionTypes<Q>) => {
const { types: computed_query_types, columns: computed_column_types_1 } = await sql(template, ...args).describe()
const computed_column_types = Object.fromEntries(computed_column_types_1.map(v => [v.name, v.type]))
const computed_description = {
types: computed_query_types,
columns: computed_column_types
}
deepStrictEqual(computed_description, description)
return await sql<DescriptionTypes<R>[]>(template, ...args).execute()
}
}
type DescriptionTypes<T> = {
-readonly [K in keyof T]: T[K] extends 23 ? number : T[K] extends 1043 ? string : T[K] extends 16 ? boolean : string;
}
const results = await typedSql(description)`SELECT * FROM users WHERE id = ${1} AND away = ${false}`
console.log(results)
console.log(results[0].type)
await sql.end(); Initial design. Hopefully not completely broken. If it holds up to it's promises I think it's awesome. |
Beta Was this translation helpful? Give feedback.
-
I'm not into typescript, so can't say, but did you see #192 ? |
Beta Was this translation helpful? Give feedback.
-
Hi,
I expected this to show the describe and then the results but it shows the describe twice. Is this intended behaviour and is there a way to do what I want?
Beta Was this translation helpful? Give feedback.
All reactions