Skip to content

Instantly share code, notes, and snippets.

@Sharaal
Last active April 7, 2021 11:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Sharaal/742b0537035720dba7bc85b6bc7854c5 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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