Show HN: Pg-typesafe – Strongly typed queries for PostgreSQL and TypeScript
69 points| n_e | 12 days ago |github.com
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.
noduerme|12 days ago
`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?
n_e|12 days ago
In another style, postgres.js uses calls such as sql`select * from t where id = ${variable}` (which is safe because it's a tagged template, not string interpolation).
WorldMaker|11 days ago
Of course, it potentially makes debugging the query from the database side a little harder because the query itself in its running form is still going to show the $1 and $2 placeholders so you'd have to count "holes" to figure which is which when trying to grep which source line is generating that query. I know that's why some frown on this template-based auto-placeholders because they want the code to better resemble the queries as they run in Postgres.
(Also yeah, it might be nice if Postgres also supported named placeholders like some of the other SQL databases do.)
wvbdmp|12 days ago
I.e.
Query("select * from MyTable where Id = @Id", myEntity)
The idiom is to use anonymous objects which you can new up inline like “new { id, age = 5 }”, where id is an existing variable that will automatically lend its name. So it’s pretty concise.
The syntax is Sql Server native (which supports named params at the protocol level), but the Npgsql dat provider converts it to PG’s positional system automatically.
nextaccountic|11 days ago
https://github.com/halcyonnouveau/clorinde/?tab=readme-ov-fi...
Latty|8 days ago
barishnamazov|12 days ago
n_e|12 days ago
I've used kysely before creating pg-typesafe, and came to the conclusion that writing SQL directly is more convenient.
A query builder works well for simple cases (db.selectFrom("t").where("id","=","1") looks a lot like the equivalent SQL), however, for more complicated queries it all falls apart. I often had to look at the docs to find how to translate some predicate from SQL to the required idiom. Also, I don't think kysely can automatically infer the return type of PostgreSQL functions, while pg-typed does (it asks PostgreSQL for it).
ZiiS|12 days ago
1-more|12 days ago
aryonoco|12 days ago
https://learn.microsoft.com/en-us/dotnet/fsharp/tutorials/ty...
SQLProvider is probably the most well known one: https://fsprojects.github.io/SQLProvider/
It’s really beautiful. You get type safety with SQL. If your code compiles, you guaranteed to have valid executable both F# code and SQL. Also you get to create composable queries.
And there are other, thinner/leaner type providers as well. My favourite Postgres one is: https://github.com/Zaid-Ajaj/Npgsql.FSharp
This simple sample executes query and read results as table then map the results
open Npgsql.FSharp
type User = { Id: int FirstName: string LastName: string }
let getAllUsers (connectionString: string) : User list = connectionString |> Sql.connect |> Sql.query "SELECT * FROM users" |> Sql.execute (fun read -> { Id = read.int "user_id" FirstName = read.text "first_name" LastName = read.text "last_name" })
n_e|12 days ago
I see they use the same global approach as pg-typed (asking for a ParameterDescription / RowDescription, which aren't usually exposed by the PG drivers), but there are interesting differences in the details. Also this made me realise that I could also type enums automatically.
afidrya|12 days ago
n_e|12 days ago
It would be quite easy to extract the queries to compute the types, but TypeScript doesn't handle tagged template literals well enough to link the query passed to the sql`` template to the return type.
kristiandupont|12 days ago
The advantage to your approach (I guess) is increased type safety for complex queries, trading off the loss of "fundamental" types with, say, branded ID types? I guess the two approaches are quite complementary, perhaps I should try that.
* https://github.com/kristiandupont/kanel
n_e|11 days ago
Regarding the nominal/branded types, the typegen is configurable, so instead of e.g. mapping oid 20 to a bigint, you could map the field id of table foo to Foo["id"] from kanel.
see this example https://github.com/n-e/pg-typesafe?tab=readme-ov-file#type-j...
blue_pants|11 days ago
Do you manually keep them in-sync (that's what I'm leaning into as the most practical solution)? Do you introspect the DB schema? Or maybe use something like Drizzle which autogenerates sql migration to keep the db schema in-sync
owlstuffing|12 days ago
1. https://github.com/manifold-systems/manifold/blob/master/man...
johnfn|12 days ago
netghost|12 days ago
I'm curious if there are any good patterns for dealing with dynamic query building or composing queries?
stephen|12 days ago
const { date, name, status } = args.filter;
await em.find(Employee, { date, name, employer: { status } });
Where the "shape" of the query is static, but `em.find` will drop/prune any filters/joins that are set to `undefined`.
So you get this nice "declarative / static structure" that gets "dynamically pruned to only what's applicable for the current query", instead of trying to jump through "how do I string together knex .orWhere clauses for this?" hoops.
n_e|12 days ago
For now, I type these manually, which is acceptable for my usage as they are pretty rare compared to static queries.
semiquaver|12 days ago
n_e|12 days ago
Regarding sqlc in general, it is focused on having the SQL queries in .sql files, while pg-typed is focused on having the queries inline (though I plan to add .sql file support). I like the latter approach better, as for small queries used in only one place, it is a little cumbersome to add them to a different file and find a name for them.
MuffinFlavored|12 days ago
n_e|12 days ago
dbbk|12 days ago
tillcarlos|12 days ago
The queries look a but more clumsy then but you won’t cause problems when spelling the column names.
mkesper|12 days ago
vivzkestrel|12 days ago
retropragma|11 days ago
seivan|12 days ago
[deleted]