porsager / postgres

Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare
The Unlicense
7.04k stars 257 forks source link

How to concatinate multiple partial statements #845

Closed NPrada closed 2 months ago

NPrada commented 2 months ago

I have a dynamic array of conditions

const conditions = [
sql`age > 1`,
sql`height < 170`,
sql`hair_color = 'red'`
]

I would like to join al of these conditions with and AND and create a runnable query that looks like this:

SELECT * FROM humans WHERE age > 1 AND height < 170 AND hair_color = 'red

What is the correct way to go about it? Is it possible using this library, i could not figure it our reading the docs

henryzhang03 commented 2 months ago

bump bump

porsager commented 2 months ago

This is hopefully something you can find through docs or searching issues.

This should do it :)

const conditions = [
  sql`age > 1`,
  sql`height < 170`,
  sql`hair_color = 'red'`
]

await sql`
  select * from humans where ${ conditions.flatMap((x, i) => i ? [sql`and`, x] : x) }
`

There a many ways to dynamically generate queries, so having all ways covered in the docs is not something I have time to do (or want to), as it is highly case specific. Perhaps a separate post explaining the difference between, values, identifiers and keywords relating to dynamic query generation would help, but again - unfortunately not something I have time to do.