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

Conditional WHERE clause #860

Closed
henryzhang03 opened this issue May 3, 2024 · 1 comment
Closed

Conditional WHERE clause #860

henryzhang03 opened this issue May 3, 2024 · 1 comment

Comments

@henryzhang03
Copy link

Hi, I looked through some of the older issues regarding this but they did not solve my problem. Here is my code snippet

    let whereClause = '';

    if (fragments.length > 0) {
      whereClause = db`WHERE ${fragments.join(' AND ')}`;
    }

    const newPairs = await db`
      SELECT * FROM NewPairs
      ${whereClause ? whereClause : db``}
      ORDER BY ${db(orderBy)} ${orderDirection.toUpperCase() === 'ASC' ? db`ASC` : db`DESC`}
      LIMIT 100 OFFSET 0
    `;

fragments just contains 0 or many of these for example:

db`sell_count <= ${sellCountTo}`

I keep getting an empty response from my DB but im not sure why, even though If I write out the full query and query my DB, it returns with a populated response.

@porsager
Copy link
Owner

You can't join on an array of fragments as that will just result in a stringified version of it. Use eg. flatMap and only insert and if i !== 0. Eg xs.flatMap((x, i) => i ? [sql`and`, x] : x)

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