await db.query("SELECT user_id, COUNT(*) AS count FROM comments GROUP BY user_id");
I would like a TypeScript object that looks like: Array<{ user_id: number, count: number }> await db.query("SELECT user_id, COUNT(*) AS count FROM comments GROUP BY user_id");
I would like a TypeScript object that looks like: Array<{ user_id: number, count: number }>and it also validates the types of the parameters that go into the query
(If you mean infer solely off of queries, I don't think that's possible unless you jam a bunch of type casts into the field selection part of the query.)
So the code itself with typescript is here:
https://github.com/vramework/vramework/blob/main/backend-com...
But the general gist is we have generic crud operators that are away of what the table are and based on that know the types of what we are returned.
const {viewId } = await database.crudInsert<UserJournal>(
'user_journal',
{ viewId, userId, srcOgg: src[0], sprite: JSON.stringify(sprite), duration },
['viewId']
)
await database.crudUpdate<UserJournal>('user_journal', { srcOgg: src[0], sprite: JSON.stringify(sprite), duration }, { viewId })
const { srcOgg, sprite, duration } = await database.crudGet<UserJournal>(
'user_journal',
['srcOgg', 'sprite', 'duration'],
{ viewId, userId },
new UserJournalNotFoundError()
)https://github.com/codemix/ts-sql
import { Query } from "@codemix/ts-sql";
const db = {
things: [
{ id: 1, name: "a", active: true },
{ id: 2, name: "b", active: false },
{ id: 3, name: "c", active: true },
],
} as const;
type ActiveThings = Query<
"SELECT id, name AS nom FROM things WHERE active = true",
typeof db
>;
// ActiveThings is now equal to the following type:
type Expected = [{ id: 1; nom: "a" }, { id: 3; nom: "c" }];However, the query might contain a wild card which means the macro function will also need access to the current DB schema.
Yeah I would love that sort of tool! I think theres some magic you can do with the es6 templating parsing, but that would be a bit complex to do as a supporting library
I think such a tool would be complicated to implemented. I was thinking maybe of integrating with tagged template literals somehow. Maybe something like:
db.query(sql`SELECT COUNT(*) FROM users`)
And then some tool could parse the AST to find all the SQL and generate types.https://github.com/launchbadge/sqlx/#compile-time-verificati...
For one of my projects I check in the generated types and replace 'unknown' (from jsonb) with the specific object manually. That way the concept of any or unknown gets pushed mostly out of the codebase (for simple crud. When joining we use normal SQL queries with some helper tools that verify the fields we are picking exist). Hopefully will manage to figure out how to do with with postgres comments at somepoint.