Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a MySQL function in a Knex query?

I have a BINARY field in my table which I usually grab like this:

SELECT HEX(users.id) AS id FROM users WHERE username = ?

I recently started using Knex because I need to be able to dynamically generate WHERE clauses from objects. Here's what I tried:

knex('users').select('HEX(users.id) AS id)').where(filter);

Here's the query it generates:

select `HEX(users`.`id)` as `id` ....

And then I tried this:

knex('users').select('HEX(`users`.`id`) AS id').where(filter);

And it comes up with this:

select `HEX(``users```.```id``)` as `id` ....

How do I execute HEX() without it being mistaken for a column name?

like image 591
starleaf1 Avatar asked Jun 21 '17 15:06

starleaf1


People also ask

What is KNEX SQL?

js (pronounced /kəˈnɛks/) is a "batteries included" SQL query builder for PostgreSQL, CockroachDB, MSSQL, MySQL, MariaDB, SQLite3, Better-SQLite3, Oracle, and Amazon Redshift designed to be flexible, portable, and fun to use.

Is KNEX an ORM?

Sequelize is an ORM that includes some query builder stuff; Knex is just a query builder, not an ORM.

What does KNEX insert return?

Knex. raw insert does not return a number of rows inserted to the table. It returns empty array [] But knex.

What is KNEX schema?

The knex. schema is a getter function, which returns a stateful object containing the query. Therefore be sure to obtain a new instance of the knex. schema for every query. These methods return promises.


2 Answers

With knex letting to do quoting of identifiers it would look like this:

knex('users').select(knex.raw('HEX(??) AS id', ['users.id'])).where(filter);
like image 140
Mikael Lepistö Avatar answered Oct 27 '22 01:10

Mikael Lepistö


I've found a solution. I have to use raw() function. So my query builder will look like this:

knex('users').select(knex.raw('HEX(`users`.`id`) AS id')).where(filter);
like image 29
starleaf1 Avatar answered Oct 27 '22 01:10

starleaf1