adelsz / pgtyped

pgTyped - Typesafe SQL in TypeScript
https://pgtyped.dev
MIT License
2.98k stars 98 forks source link

Type inference for static JSON aggregates #348

Open AlexHorstkoetter opened 3 years ago

AlexHorstkoetter commented 3 years ago

We often use queries with a static JSON aggregate, for example

SELECT json_agg(json_build_object(
    'firstname': firstname,
    'age': age
)) as family
FROM persons
GROUP BY lastname

The problem is that in this case family has type JsonArray, although they could in theory have the much more concrete and useful type {firstname: string, age: number}[] We have to manually cast the JSON types which is prone to bugs. Is something like this technically feasible? If not, maybe some way to annotate the return type would be nice

adelsz commented 2 years ago

JSON aggregates are quite powerful, but unfortunately they are untyped as is. I do like the idea of introducing a special json keyword that would run type interference on all fields of the json object at compile-time and run the json aggregation at runtime.

benlongo commented 2 years ago

This would allow circumventing the issues that arise when dealing with composite types or unmapped types like ranges. Given the target language is JavaScript, I think this workaround is natural.