postgres icon indicating copy to clipboard operation
postgres copied to clipboard

Using iteration with dynamic query builder

Open devilj opened this issue 6 months ago • 0 comments

I couldn't find a way to make dynamic query builder to work with iteration - map/reduce does not seem to work nicely. TBH, I didn't spend too much time trying.

Here's an example of how I made it to work:

const 

const rows = sql`select 1 from text where TRUE and
 ${search.text?.length ? sql`and (
   ${search.text[0] ? sql`   (btt.search_text @@ phraseto_tsquery('english', ${search.text[0]}))` : sql``}
   ${search.text[1] ? sql`OR (btt.search_text @@ phraseto_tsquery('english', ${search.text[1]}))` : sql``}
   ${search.text[2] ? sql`OR (btt.search_text @@ phraseto_tsquery('english', ${search.text[2]}))` : sql``}
   ${search.text[3] ? sql`OR (btt.search_text @@ phraseto_tsquery('english', ${search.text[3]}))` : sql``}
   ${search.text[4] ? sql`OR (btt.search_text @@ phraseto_tsquery('english', ${search.text[4]}))` : sql``} 
 )` : sql``}
ORDER BY 1
`;

obviously this is horrible.

Any suggestions?

devilj avatar Aug 03 '25 22:08 devilj