Conditional WHERE clause
henryzhang03 opened this issue · comments
Henry Zhang commented
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.
Rasmus Porsager commented
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)