porsager / porsager/postgres

Cannot return SQL fragment directly from async function

Open
#1,019 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

I have async helper function which should create SQL fragment. But when I return it directly, it is treated as executable query and this of course fail badly.

Is there possibility to create only SQL fragment, which have not PromiseLike interface?

Example:

This will not work:

  async getSqlFilter(/* ... */): Promise<PendingQuery> {
     return sql`true`;
  }

Workaround – working, but ugly:

  async getSqlFilter(/* ... */): Promise<{ filter: PendingQuery }> {
     return { filter: sql`true` };
  }

Request; proposed API:

  async getSqlFilter(/* ... */): Promise<QueryFragment> {
     return sql.fragment`true`; // this cannot be executed
  }

Use case:

  async getSqlFilter(...values: string[]): Promise<QueryFragment> {
     if (values.length === 0) {
       return sql.fragment`true`; // or false, it depends :-)
     } else if (values.length === 1) {
       return sql.fragment`attribute = ${values[0]}`;
     } else {
       return sql.fragment`attribute = ANY(${values})`;
     }
  }

Is there interrest in this feature?

IMHO it's more secure to have fragment and final query separated.

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

No source file, test, or entry point is named. Start by reviewing how the sql template handles PromiseLike values and how query fragments are represented; done means a supported non-executable fragment API can be returned from an async helper without triggering query execution.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, nodejs, postgresql, typescript
Domain
backend-api-design, databases
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.