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?
Sequelize is an ORM that includes some query builder stuff; Knex is just a query builder, not an ORM.
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.
Sequelize offers a . query() method to execute raw SQL as if you were using the underlying database driver. With both the Bookshelf and Objection ORMs you get access to the raw Knex object which you provide during instantiation and can use that for its Query Builder powers.
Intro to Knex Knex. js is a “batteries-included” query builder for PostgreSQL, MySQL, SQLite3, Oracle, Amazon Redshift, and many other database drivers. We simply install the Knex library and the appropriate driver to query the database. Primarily made for Node. js, Knex supports both Node-style callbacks and promises.
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'))
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