Manu
Manu

Reputation: 4149

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?

Upvotes: 6

Views: 5910

Answers (1)

oskrgg
oskrgg

Reputation: 101

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

Upvotes: 1

Related Questions