For debugging purposes, I want to see the SQL query knex
is executing. For example, I want to view SQL that knex
produces for this code:
knex('statistics')
.del()
.where({
'stats': 'reddit',
});
https://knexjs.org/guide/interfaces.html#other
knex('statistics')
.del()
.where({
'stats': 'reddit',
}).toSQL().toNative()
toNative().bindings
Dec 15, 2021 at 11:18
.toString()
or .toQuery()
(see my answer as it is more comprehensive)
Jul 4, 2022 at 22:20
.toString()
/ .toQuery()
that is not the query that knex runs when the builder is triggered. Outputted string might be working SQL some times and sometimes it is not. Knex does not do value escaping correctly in every case when rendering string from builder. .toQuery()
and .toString()
are aliases to each other. Both should be used only for debugging. .toSQL().toNative()
returns the templated SQL query string for the used dialect and corresponding bindings. That should be the exact query that is executed by the knex when the builder is triggered.
Jul 5, 2022 at 19:20
knex('statistics')
.del()
.where({
'stats': 'reddit',
}).toString();
toString()
is the same way as .toSQL().toNative()
but shorter. Do you really think that there is one right answer only?
Dec 16, 2020 at 5:00
.toString()
and .toQuery()
return the full SQL query as a string
For your example:
knex('statistics')
.del()
.where({
'stats': 'reddit',
}).toString();
returns:
delete from "statistics" where "stats" = 'reddit'
Whereas .toSQL().toNative()
returns an object:
knex('statistics')
.del()
.where({
'stats': 'reddit',
}).toSQL().toNative();
{
sql: 'select * from "books" where "author" = $1',
bindings: [ 'John Doe' ]
}
To print all queries then passing a debug: true
flag on your initialization object will turn on debugging
for all queries.
knex({
client: 'mysql',
debug: true,
connection: {
host: '127.0.0.1',
port: 3306,
user: 'root',
password: '',
database: ''
}
})
In my case toSQL()... does not produce the "parsed" SQL string, only toString() works, I'm not sure if this depends on one's specific usage of the Query Builder.