I'm new to the world of sequelize. Let's say I need to run a query (on postgres) like this one:
select to_char(column1, 'HH:MM:SS') from table1 where param1 = :param
Using sequelize I have to setup the raw query like this:
db.sequelize.query(query, { replacements: { param: 'whatever' }, type: db.sequelize.QueryTypes.SELECT }).then((list) => { ... });
I'm having trouble because the colon character appears in the query string; sequelize seems to interpret those colons for replacements.
Is there any special syntax I have to use, in order for sequelize to parse correctly the string to_char(column1, 'HH:MM:SS')
?
Sequelize instance comes with the query() method which you can use to run a raw query. The syntax of the method is as shown below: const [results, metadata] = await sequelize. query( "Your query here", { options } );
In short, this story shared my experience in working with Sequelize raw options, setting raw to true will change your boolean expected field to number, and lastly, we could use a better approach which is toJSON to achieve my desired outcome.
Hope I'm not too late but I experienced the same issue and what I did was to put the string format in the replacement. Using your example, it'll be like:
select to_char(column1, :format) from table1 where param1 = :param
And the Sequelize part:
db.sequelize.query(query, { replacements: { param: 'whatever', format: 'HH:MM:SS' }, type: db.sequelize.QueryTypes.SELECT }).then((list) => { ... });
I couldn't find the 'official' way to do it so this is like a tiny roundabout method.
Maybe it's late, but can be useful for others who find this question.
The best approach I found is using "Bind Parameter" instead of "Replacements". For details check "Bind Parameter" section in Sequelize -> Raw queries.
For your example:
const query = `select to_char(column1, 'HH:MM:SS') from table1 where param1 = $param`
db.sequelize.query(query, {
bind: {
param: 'whatever'
},
type: db.sequelize.QueryTypes.SELECT
}).then((list) => { ... })
The idea is to replace :
by $
and use bind
instead of replacements
in query options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With