Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot return SQL fragment directly from async function #1019

Open
langpavel opened this issue Jan 24, 2025 · 1 comment
Open

Cannot return SQL fragment directly from async function #1019

langpavel opened this issue Jan 24, 2025 · 1 comment

Comments

@langpavel
Copy link

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.

@porsager
Copy link
Owner

It's only executed if you await it, so just don't make your getSqlFilter function asynchronous.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants