Lin Du
Lin Du

Reputation: 102537

What's the difference between knex.raw() and knex.schema.raw()?

knex.raw(sql, bindings) and knex.schema.raw(statement).

It seems that these two functions have different signature.

If they are equivalent, how can I use knex.schema.raw(statement) and pass bindings to it?

Upvotes: 9

Views: 5059

Answers (1)

Mikael Lepistö
Mikael Lepistö

Reputation: 19728

knex.raw creates query builder instance which can be executed right away.

With knex.schema.* things work a bit different manner. Knex schema methods creates an array of queries, which are then executed one by one when schema builder is resolved.

So for example if you do knex.schema.createTable(t => ...).raw('DROP ALL').toSQL() you will see that there are multiple queries generated and they all will be executed when schema builder is triggered.

If you do just await knex.schema.raw('SELECT 1') or await knex.raw('SELECT 1'), there won't be any differences. But with knex.schema.raw you can also do:

await knex.schema.raw('SELECT 1').raw('SELECT 2');

Which returns an array where results of both of the queries are found. So it is totally possible to exploit that feature also for running multiple queries one after another like this:

await knex.schema
  .raw('?', [knex('table1').where('id', 1)])
  .raw('?', [knex('table2').where('id', 2)]);

Also knex.schema.raw doesn't return QueryBuilder, but it returns SchemaBuilder with different methods available.

So knex.schema.raw cannot be used as a part of normal queries for example in knex('table').where(knex.raw('id = 1'))

Upvotes: 3

Related Questions