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
Helper for join array of SQLStatements? #32
Comments
This is my implementation for that: function joinStatements(separator: SQLStatement, parts: SQLStatement[]): SQLStatement {
const result = SQL``
for (let i = 0, count = parts.length; i < count; i++) {
result.append(parts[i])
if (i < count - 1) {
result.append(separator)
}
}
return result
} |
I just ran into this same exact need. My use case is that I want my query to insert multiple rows like this: INSERT INTO authors (id, user_handle, first_name, last_name)
VALUES ($1, $2, $3, $4), ($5, $6, $7, $8), ($9, $10, $11, $12), ... So I played around with monkey-patching a new SQLStatement.prototype.appendAll = function(statements:(SQLStatement|string|number)[], delimiter:string = ' ') {
for (let i = 0; i < statements.length; i++) {
this.append(statements[i])
.append(i < statements.length - 1 ? delimiter : '')
}
return this
} Which allowed me to do: const query = sql`INSERT INTO authors (id, user_handle, first_name, last_name) VALUES `
.appendAll(authors.map(a => sql`(${a.id}, ${a.authorHandle}, ${a.userHandle}, ${a.firstName}, ${a.lastName})`), ', ') Another option would be add this functionality to the @felixfbecker What do you think? I'd love to submit a PR (along with tests and type updates) if you're okay with this. |
For anyone stumbling upon this, toAppend.reduce((prev, curr) => prev.append(delimeter).append(curr), statement) |
For me, the main difference between |
@felixfbecker: Like @Janpot said, it would be really nice with a
This is really easy to read and write IMO, allows you to be immutable and you don't have to check if you are on the last value or not to know if you should add a |
Just ran into this: need to join array of condition parts with
and
separator:It is not big deal to write function for that, but maybe it is better to have this one in the library? What do you think about it?
The text was updated successfully, but these errors were encountered: