Show HN: Pg-typesafe – Strongly typed queries for PostgreSQL and TypeScript

27 points - today at 6:15 PM


Throughout my career, I tried many tools to query PostgreSQL, and in the end, concluded that for what I do, the simplest is almost always the best: raw SQL queries.

Until now, I typed the results manually and relied on tests to catch problems. While this is OK in e.g., GoLang, it is quite annoying in TypeScript. First, because of the more powerful type system (it's easier to guess that updated_at is a date than it is to guess whether it's nullable or not), second, because of idiosyncrasies (INT4s are deserialised as JS numbers, but INT8s are deserialised as strings).

So I wrote pg-typesafe, with the goal of it being the less burdensome: you call queries exactly the same way as you would call node-pg, and they are fully typed.

It's very new, but I'm already using it in a large-ish project, where it found several bugs and footguns, and also allowed me to remove many manual type definitions.

Source

Comments

noduerme today at 11:34 PM
Somewhat off topic, as someone who hasn't used PostgreSQL and only has experience with mysql/MariaDB... I've never liked writing queries with numbered parameters from an array with placeholders like $1 in this example. I find them much easier to read and debug when I pass them with string keys, basically:

`UPDATE t SET x=:x WHERE 1` `{x:42}`

I found that the original node-mysql didn't even allow this, so I wrote my own parser on top of it. But I don't see this style of binding used in examples very often. Is it frowned upon for some reason?

afidrya today at 11:32 PM
Is there a way to make this work with https://github.com/porsager/postgres ? It's very close to raw SQL but with safe substitutions. I use it with Zod, but it would be great to have the types derived automatically.
1-more today at 11:03 PM
If you're into Haskell prior art, there's postgresql-typed https://hackage.haskell.org/package/postgresql-typed-0.6.2.5... where you write queries, it safely(?) puts in your variables, and you automatically get back typed values.
barishnamazov today at 10:24 PM
How is this different than kysely + kysely-codegen (or hand-made types)?
dbbk today at 11:28 PM
Just use Drizzle
semiquaver today at 11:00 PM
How is this different from sqlc with sqlc-gen-typescript?