Search code examples
mysqlnode.jsknex.js

Convert mySQL query to KNEX


I am converting series of queries to Knex syntax. I am having problem with this query:

SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
FROM store_failure_log
WHERE reviewed = 0
AND create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW();

More precisely this line:

SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id

I have this Knex in place:

knex('store_failure_log')
        .select('id', 'reviewed', 'log_reference', 'CONVERT(notification USING utf8)', 'create_time', 'update_time', 'store', 'user_id').convert('notification USING utf8')
        .where('reviewed', 0)
        .where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))

that produces this sql query:

select `id`, `reviewed`, `log_reference`, `CONVERT(notification USING utf8)`, `create_time`, `update_time`, `store`, `user_id` from `store_failure_log` where `reviewed` = 0 and create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()

Problem is in the: Convert(notification USING utf8).

The query is not valid, since the Convert is in parentheses. How can I write it with the knex?

In general how do I include SQL function calls in the KNEX syntax?


Solution

  • You can use raw to include SQL function calls in your Knex query, like you've already done in your where:

    knex('store_failure_log')
            .select(knex.raw('id, reviewed, log_reference, CONVERT(notification USING utf8), create_time, update_time, store, user_id'))
            .where('reviewed', 0)
            .where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))