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

postgres.js needs something like slonik's sql.join() for building dynamic queries #807

Open
DanielFGray opened this issue Feb 15, 2024 · 5 comments
Labels
enhancement New feature or request

Comments

@DanielFGray
Copy link

DanielFGray commented Feb 15, 2024

postgres.js gives us parameterized tagged templates and the ability to nest sql partials, and this is fantastic, but I think it is missing a piece of the puzzle:

I want need to be able concat partials together (that may contain query parameters), usually with some delimiter (eg whitespace, or a comma, or maybe an sql operator)

slonik provides something like:

sql.join = (a: PendingQuery[] | Helper[], p: PendingQuery): PendingQuery {...}

and I think it would be amazing if this were a first-class feature in postgres.js

this should allow things like

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

Yeah, I think it makes sense to add, but I've just been doing this when needed

xs.flatMap((x, i) => i ? [sql`, `, x] : x)

You can fairly quickly make a function to use instead if you feel like it - eg 😋

sql.join = (xs, joiner) => xs.flatMap((x, i) => i ? [joiner, x] : x)

I'll keep the issue open for now.

@porsager porsager added the enhancement New feature or request label Feb 17, 2024
@DanielFGray
Copy link
Author

sql.join = (xs, joiner) => xs.flatMap((x, i) => i ? [joiner, x] : x)

oh interesting! i would never have come up with that on my own

do you have any reservations about adding this as a core feature?

@DanielFGray
Copy link
Author

and if no reservations, would you accept a PR adding this as a core feature?

@davepar
Copy link

davepar commented Jun 7, 2024

It would be great to at least add the work-around to the docs. It wasn't obvious to me how to join sql fragments with a comma. Glad I found this.

@DanielFGray
Copy link
Author

DanielFGray commented Jun 7, 2024

i'm working on a PR

anyone want to bike-shed over join vs concat to avoid confusion with sql joins?
or concat_ws to use actual postgres api 😁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants