Last active
April 7, 2021 11:20
Star
You must be signed in to star a gist
SQL Tagged Template Literals with Node.js and `pg`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SQL Tagged Template Literal Library for
pg
'sclient.query
: https://github.com/Sharaal/sql-pg.