Amiga500
Amiga500

Reputation: 6141

Change the output of the Knex rawquery

I am forced to use raw query with the Knex, since there is an issue with the union

One query, is not that bad. But now I have other type of issue.

All other Knex queries (non raw ones), they simply return an array with the results

For example:

knex('user_subscription_plan')
        .select('*')
        .where('paused_days', '>', 91)
        .where('status', 'N_PAUSED')

will return an array, empty of there is no results.

However, if I run raw query, for example:

mySqlClient.raw('select * from user')

it will return an array, with two arrays inside it. First one is the normal result, while other one contains some catalogue definitions.

That interferes with my logic. At the end of each call to knex, I have:

if (result.length > 0) {
   // send email
}

Now, when I run the raw Query, the result is always greater then zero. How can I tell Knex not to send the catalogue definitions, in other words, just send results back, exactly like it does on non raw queries?

Upvotes: 2

Views: 5158

Answers (3)

Arfina Arfwani
Arfina Arfwani

Reputation: 176

If you want to get the same result as the select result, use select and pass your raw query as an argument without "SELECT" keyword. In your example, instead of doing:

mySqlClient.raw('select * from user')

You should do:

mySqlClient.select( mySqlClient.raw(' * from user') )

Upvotes: 0

Mikael Lepistö
Mikael Lepistö

Reputation: 19728

You should do it like @horatiu-jeflea answered.

Though we could add some way to knex to tell that also result of raw query should be parsed with default result parser. To make that way to appear in knex you could open feature request to its github issues.

Also there is https://knexjs.org/#Installation-post-process-response which you should be able to override to handle your raw query results are post processed.

Upvotes: 0

Horatiu Jeflea
Horatiu Jeflea

Reputation: 7414

According to https://github.com/knex/knex/issues/1802 there is no way around it, just do

mySqlClient.raw('select * from user')[0]

Upvotes: 2

Related Questions