Knex: toString debugging when using Bookshelf

Created on 30 Dec 2014  ·  3Comments  ·  Source: knex/knex

I'm using bookshelf->knex->pg and need to dig deeper into some of the SQL queries that are being generated. I would like to see the toString() outputs for every query that passes through knex, i.e. without any $1, $2 etc. Is there a way to enable this without a monkey patch, or a patch which can do this simply?

question

Most helpful comment

Hi, and thanks for the quick and positive responses. FYI I modified this a little to correct a typo plus make it copy-and-pasteable:

  knexInstance.on('query', function (query) {
    var params = query.bindings.slice();
    var q = query.sql.replace(/\?/g, function () {
      return '\'' + params.shift() + '\'';
    });
    console.log(new Date().toISOString(), '\n', q, '\n');
  });

All 3 comments

You could listen to the query event of your knex instance and then interpolate the bindings:

var bindingRegex = /\?/g;
knexInstance.on('query', function (query) {
  var params = query.bindings.slice();
  var q = query.sql.replace(bindingRegex, function () {
    return params.unshift();
  });

  console.log(new Date().toISOString(), '\n', q, '\n');
});

Is this what you are looking for?

Debugging is pretty high on the priority list of things that need work.

I'm currently working on retooling a lot of the internals of knex & bookshelf to make things a lot simpler with an emphasis on debugging and robust query generation. Should see some new things that make this available without temporary patches showing up in the next month or two,

The snippet @johanneslumpe shared should definitely help in the meantime

Hi, and thanks for the quick and positive responses. FYI I modified this a little to correct a typo plus make it copy-and-pasteable:

  knexInstance.on('query', function (query) {
    var params = query.bindings.slice();
    var q = query.sql.replace(/\?/g, function () {
      return '\'' + params.shift() + '\'';
    });
    console.log(new Date().toISOString(), '\n', q, '\n');
  });
Was this page helpful?
0 / 5 - 0 ratings

Related issues

legomind picture legomind  ·  3Comments

npow picture npow  ·  3Comments

mtom55 picture mtom55  ·  3Comments

saurabhghewari picture saurabhghewari  ·  3Comments

nklhrstv picture nklhrstv  ·  3Comments