Skip to content

Instantly share code, notes, and snippets.

@Sharaal
Last active Apr 7, 2021
Embed
What would you like to do?
SQL Tagged Template Literals with Node.js and `pg`
// with a sql tagged template literal use parameters directly in the sql query
const id = 5
const name = 'new name'
client.query(sql`
UPDATE users SET name = ${name} WHERE id = ${id}
`)
// text: 'UPDATE users SET name = $1 WHERE id = $2'
// values: [ 5, 'new name' ]
// very simple version of the tag function, advanced can be find in the comment
function sql(textFragments, ...values) {
let text = ''
for (let i = 0; i < textFragments.length; ++i) {
if (text !== '') {
text += `$${i}`
}
text += textFragments[i]
}
return { text, values }
}
@Sharaal

This comment has been minimized.

Copy link
Owner Author

@Sharaal Sharaal commented Feb 15, 2019

SQL Tagged Template Literal Library for pg's client.query: https://github.com/Sharaal/sql-pg.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment