3 ms·
``` const users = await sql` select name, age from users where age > ${ age } ` ``` Do template literals like this in JS work differe
by rubyist5eva 5y ago
```
const users = await sql`
select
name,
age
from users
where age > ${ age }
`
```
Do template literals like this in JS work differently than just straight up string interpolation? As a rails dev this set off alarm bells.
- porsager 5y agoYeah, when a function is called as a "tagged template literal"[1] the function takes control over how the parameters are handled. Postgres.js uses this to replace the value with $1, $2, etc and send over the value as parameters to the database, thereby preventing any chance of SQL injection[2]. [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... [2] https://github.com/porsager/postgres#await-sql---result https://github.com/porsager/postgres#await-sql---result
- rubyist5eva 5y agonice!
- lowwave 5y agogreat to use template lilerals, but any way to use in perpare statement in order to escape sql injection etc type of stuff?
- lowwave 5y agoJust saw this on the page: >Parameters are automatically extracted and handled by the database so that SQL injection isn't possible. No special handling is necessary, simply use tagged template literals as usual. Dynamic queries and query building can be seen in the next section. // todo this is great! Can't wait to give a try.