Skip to content

Cannot return SQL fragment directly from async function #1019

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

Open
langpavel opened this issue Jan 24, 2025 · 2 comments
Open

Cannot return SQL fragment directly from async function #1019

langpavel opened this issue Jan 24, 2025 · 2 comments

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.

@langpavel
Copy link
Author

But I need my filter function to be asynchronous because it may conditionally do async stuff.

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