porsager / postgres

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

feat: sql.join #905

Open DanielFGray opened 1 week ago

DanielFGray commented 1 week ago

closes #807, to add sql.join:

let dynamicFilters = [
  sql`somecol = ${somevalue}`,
  sql`col2 = ${v2}`
];
const dynamicColumns = [sql('somecol'), sql('col2')];
await sql`
  select ${sql.join(sql`, `, dynamicColumns)} from t
  where ${sql.join(sql` and `, dynamicFilters)};
`;

i'm not 100% sure the types are right, and I couldn't get the tests to run, so those probably need some work

DanielFGray commented 1 week ago

if you have a weird workaround you can try this fix in your own projects

npm i github:danielfgray/postgres.js

@Destreyf @davepar your feedback would be appreciated!

DanielFGray commented 1 week ago

I also really want to enable currying to allow things like

const and = sql.join(sql` and `)
and(sql`...`, ...fragments)

which could be as simple as

- function join(sep, xs) {
+ function join(sep, ...xs) {
+   if (!xs) return join.bind(null, sep)
    return xs.flatMap((x, i) => {

but this would probably also need further bike-shedding

I also wonder if the API could be further improved to simply allow

const and = sql.join` and `
const params = and(f1, f2, f3)
// would work the same as
const params = sql.join` and `(f1, f2, f3)

I'm not sure that postgres.js goals are to be a whole query builder, but it seems like we can add a lot of expressivity with a few tweaks to a simple feature

but currying is likely to increase the complexity of the TS types and perhaps make the API more complex and difficult to document :balance_scale:

phosmium commented 1 week ago

neat feature, hope this makes it in +rep