postgres icon indicating copy to clipboard operation
postgres copied to clipboard

Separate types and docstrings for query helpers

Open FeldrinH opened this issue 3 years ago • 2 comments

Currently the sql query helpers have a very generic docstring and a very complex and confusing type signature: image This makes using the helpers fairly confusing and error prone (at least for me). In particular, it makes it hard to know what a helper does when reading existing code.

Is there a possibilty to split the different query helpers into different function overloads so that they can each have their own type and docstring?

Or maybe it would be possible to do something like what slonik does and have the helpers be separate functions under sql (https://github.com/gajus/slonik#user-content-slonik-query-building).

FeldrinH avatar Sep 17 '22 16:09 FeldrinH

That's what types used to do, but the sql tag is so generic that without this wizardry, typescript sometimes confuses tagged template string calls with helpers and inversely, and errors reporting where broken/unreadable. Also, helpers format depends on the sql context, so it's really hard to provide useful types for helpers. Actually, the correct overload is

interface Sql<TTypes> {
  // ...

  (first: any, rest: any): Helper;

  // ...
}

The issue with this overload is that it matches the tagged template string call so that when an invalid parameter is passed as argument (e.g. sql`SELECT ${Symbol()}`;), no errors are reported because TS fallback to the following matching overload :confused: The solution could be to not use any for first, but depending on the context, the sql tag may allow any values (for escaping them for instance). Using this wizardry allows to force the overload to always fail when the first argument is exactly a TemplateStringArray, but also to provide more detailed types thanks to conditional types ;)

As you suggested, the best would be to split helpers into separate functions, but that would be a huge breaking change (maybe not if the old behavior is kept intact :thinking:)

@porsager Do you have some feedback on this?

Minigugus avatar Sep 19 '22 05:09 Minigugus

Yeah, I'm leaning towards adding explicit helper methods with v4

porsager avatar Jun 25 '23 23:06 porsager