adelsz / pgtyped

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

ts-pg-promise: typed queries for pg-promise without runtime dependencies #559

Open ml-mave opened 8 months ago

ml-mave commented 8 months ago

Hi! This PR is a proposal for a new transform mode in pgtyped ("ts-pg-promise") which adds support for generating types for pg-promise queries without requiring any runtime dependencies[^1]. In our codebase, we use pg-promise a lot and wanted an easy way to get better type safety for SQL queries, and after a bit of research it turned out pgtyped was pretty close to what we would like to have.

The generator searches for tx.{none,one,oneOrNone,many,manyOrNone} calls in source files (where the name tx is configurable as an array of possible names) and inspects the first argument of the call.

Queries are automatically named based on the name of the enclosing function. If a function contains several queries or if the function name is not unique across all source files, the conflicting names are disambiguated with a number.

The generator creates an interface containing method signatures for each query so that:

The generator adds 5 fallback overloads to make error messages a little less bad (but they are still not great). Based on some testing, TypeScript always reports the last overload if the argument types don't match, so it would probably require changes to TS compiler itself to improve error messages. Ideally, the overload candidate should be the one whose first parameter passes type check.

Raw and identifier bindings (e.g. $(foo^), $(bar~)) are not supported (but they are still parsed so that a proper warning message is printed).

The generated parameter field types are non-optional and by default not nullable. It seems there was no existing mechanism for adjusting nullabilities of individual parameters, so for this mode we've added a magic comment /*nullable*/ so you can have for example:

SELECT foo
FROM bar
WHERE baz = $(baz)/*nullable*/

Configuration options for ts-pg-promise mode:

There's also some other new general configuration options:

Documentation and tests are incomplete/lacking, but we wanted to send this PR for initial feedback now. Sorry for not opening an issue first, and thanks for reading! =)

[^1]: The only required runtime change is that trailing ! or ? in result column names must be stripped off because pgtyped uses this syntax for adjusting result column nullabilities manually.

vercel[bot] commented 5 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
pgtyped ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 18, 2024 3:17pm