4 ms·
You mean you don't see tagged templates used at all? Or just not for sql? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#t
by voxic11 3y ago
You mean you don't see tagged templates used at all? Or just not for sql?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
> Even this example - will this create a prepared statement or insert a correctly escaped value into the SQL string?
That tagged template doesn't evaluate to a string, it evaluates to a parameterized query object that contains the parameterized query string and the parameter values. You pass it to the mysql library and it executes the parameterized query.
const query = SQL`SELECT author FROM books WHERE name = ${book} AND author = ${author}`
typeof query // => 'object'
query.text // => 'SELECT author FROM books WHERE name = $1 AND author = $2'
query.sql // => 'SELECT author FROM books WHERE name = ? AND author = ?'
query.values // => ['harry potter', 'J. K. Rowling']
- The_Colonel 3y ago> You mean you don't see tagged templates used at all? Or just not for sql? Not at all. Thanks for the explanation, so it's not just escaped param substitution. Which brings up the question if you can combine normal text substitution with SQL substitution, e.g.: SELECT author FROM books WHERE name LIKE '%${book}%' AND author = ${author} AND ${extraCondition} (it's pretty common to have to join query segments)
- kaba0 3y agoThe text processor does have context as well, so there is nothing preventing someone from doing just that. Not sure if there will be a standard SQL processor, though.
- deleted 3y ago[deleted]
- voxic11 3y agothe library recommends you do that this way const query = SQL`SELECT * FROM books` if (params.name) { query.append(SQL` WHERE name = ${params.name}`) } query.append(SQL` LIMIT 10 OFFSET ${params.offset || 0}`) or if you need raw values like a table name then just pass append a string. db.query(SQL`SELECT * FROM "`.append(table).append(SQL`" WHERE author = ${author} ORDER BY ${column} `).append(order))