porsager / porsager/postgres

Wrapping the SQL Tag Function

Open
#1,059 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Typescript
Dominant language
JavaScript
Stars
8.7k
Forks
374
Avg merge
11d 16h
Merged PRs (30d)
1

Description

I have a load of simple queries to define, each returning one or many models which I have Typescript types for. At present I’m doing something like:

findById: async (id) => {
  const [user] = await sql<User[]>`
    SELECT *
    FROM users
    WHERE id = ${id}
  `
  return user ?? null
},

I would like to clean up the call sites to make the queries a bit more readable by creating a couple of helpers that do the whole thing inline — something like the following:

findById: async (id) => 
  await one`
    SELECT *
    FROM users
    WHERE id = ${id}
  `,

findMany: async (type) => 
  await many`
    SELECT *
    FROM users
    WHERE type = ${type}
  `,

But figuring out what types the wrapper tag functions need to have is a bit beyond me after looking through the Sql type’s definition.

All I really want to do is for many, pass through the result and cast it to the caller’s desired type, and for one, unwrap the first result and cast that to the caller’s desired type, which would be T | null.

Has anyone wrapped the sql tag function before and has the types handy, or knows how to do this?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Sql type definition and the sql tag API mentioned in the issue, then inspect how tagged-template results are typed. Confirm how wrappers could preserve interpolations while exposing many results or the first result as T | null; done means TypeScript callers can use the requested one and many forms with the intended inferred types.

Written by the indexing model from the issue text.

Assessment

Tech stack
postgresql, typescript
Domain
databases
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.