Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid single quotes in sequelize query with replacements?

I want to do a raw query using Sequelize and use replacements to avoid sql injection:

var sequelize = require('sequelize');
sequelize.query("SELECT * FROM table where name =:name ORDER BY :age:direction",
{replacements:{name:"test", age:"age", direction:"desc"}, type: sequelize.QueryTypes.SELECT })  

This will be converted to following query

SELECT * 
FROM table 
WHERE name = 'test' 
ORDER BY 'age' 'desc'  

Since the order by column is having single quotes and direction also with single quotes, postgres throws error

Can anyone suggest how do I solve this problem with replacements in place?

like image 962
Manu Avatar asked Jul 23 '15 09:07

Manu


1 Answers

As a workaround I created the query and the sort order by separately and then concatenate them as follow:

const query= `SELECT * FROM table where name =:name ORDER BY :age`;
let sortOrder = `DESC`
sequelize.query(`${query} ${sortOrder}`, {replacements:{name:"test", age:"age"}, type: sequelize.QueryTypes.SELECT })

being there is just about play with the sortORder

like image 135
oskrgg Avatar answered Oct 17 '22 01:10

oskrgg