Search code examples
nestedsubquerysequelize.js

nested SELECT query in Sequelize


How do I make a query with a nested SELECT statement protected from sql injection in Sequelize?

An example of a conditional query for MySQL:

SELECT * FROM cities WHERE country_id IN (SELECT id FROM countries WHERE lang = 'French');

Solution

  • QueryGenerator.selectQuery () saves from sql injections:

    const lang = 'French';
    const subQuery = sequelize.dialect.QueryGenerator.selectQuery('countries',
        {
            attributes: ['id'],
            where: {
                 lang: lang,
            }
        })
        .slice(0,-1); // to remove the ';' from the end of the SQL
    
    CitiesModel.findAll( {
        where: {
            country_id: {
                [Op.in]: sequelize.literal('(' + subQuery + ')'),
            }
        } 
    } );