Sequelize.js - build SQL query without executing it

Viewed 2649

Is there a way to get Sequelize to build a query with the replacements (so I'll be able to use their SQL injection cleanup) and just get the raw SQL query, without executing it?

3 Answers

You can just call the QueryGenerator with the type of query you want to generate. For example a selectQuery:

    const sql = MyModel.QueryGenerator.selectQuery(
        MyModel.getTableName(), {
        where: {
            someAttribute: "value"
        },
        attributes: ["other", "attributes"]
    },
        MyModel);

There's also insertQuery, updateQuery, deleteQuery too.

It looks like this feature isn't implemented yet, but there are some users trying to push the issue forward.

See github issue.

it's undocumented, but I use next way (Sequelize ver. 5.2.13):

let tableName = myModel.getTableName(options);
let qi = myModel.QueryInterface;
options.type = 'SELECT';
options.model = myModel;
var sql = qi.QueryGenerator.selectQuery(tableName, options, myModel);
Related